PHP中无效正则表达式求助:自定义匹配模式报错原因
Let's break down why your regex is throwing an "invalid Regular Expression" error and how to fix it:
1. Syntax Error: Incorrect String Concatenation
You're using . to join your regex segments (like 'A/[.]+;' . 'B/[.0-9]+;'), which is invalid syntax in almost all programming languages (Python, JavaScript, Java, etc.).
Most languages use the + operator for string concatenation. For example, in Python, you'd write:
pattern = 'A/[.]+;' + 'B/[.0-9]+;' + 'C/[0-9]+;' + 'D/[.]+;' + 'E/[.0-9]+;' + 'F/[.a-zA-Z]+;'
Using . instead of + causes a syntax error before the regex is even parsed, which is likely the immediate cause of your "invalid Regular Expression" message.
2. Logical Matching Errors
Even if you fix the concatenation, your regex won't match your target string because some character classes don't align with the content you're trying to capture:
A/[.]+;: This only matches one or more literal dots afterA/, but your target hasA/U88;(letters and numbers, no dots). Replace[.]+with[0-9a-zA-Z]+to match alphanumeric characters here.D/[.]+;: Similarly, this only matches dots, but your target hasD/4ND8;(alphanumeric characters). Change[.]+to[0-9a-zA-Z]+to correctly match this segment.
Corrected Regex Example
Here's a fixed version that will match your target string A/U88;B/12.01.5;C/123456;D/4ND8;E/3.56.78;F/Sa.yA;:
# Fixed regex with correct concatenation and matching logic fixed_pattern = r'A/[0-9a-zA-Z]+;B/[0-9.]+;C/[0-9]+;D/[0-9a-zA-Z]+;E/[0-9.]+;F/[a-zA-Z.]+;'
A quick note: You don't need to escape . inside character classes ([])—it already matches the literal dot, which you had correct for segments B, E, and F.
内容的提问来源于stack exchange,提问作者user284602

