正则匹配问题:无法匹配字符串末尾的字母数字字符
First, let's break down why your current regex /^(AB)(\d+)([A-Za-z][0-9])?/ isn't capturing those trailing characters:
- The third group
([A-Za-z][0-9])?only matches an optional pair of a letter followed by a digit. - In your test case
AB57933A, the trailing character is just a single letter (no digit after it), so this group doesn't trigger. Similarly,AB57933AbChas multiple letters without trailing digits in sequence, which doesn't fit the letter-digit pair pattern.
To fix this, we need to adjust the third group to match any combination of letters and digits (in any order, zero or more times) instead of the restrictive letter-digit pair. Here's the revised regex:
str.match(/^(AB)(\d+)([A-Za-z0-9]*)/)
What Changed:
- Replaced
([A-Za-z][0-9])?with([A-Za-z0-9]*):[A-Za-z0-9]matches any uppercase letter, lowercase letter, or digit.*means "zero or more occurrences"—so this group will capture any trailing alphanumeric characters (including none, if the string ends after the digits).
Testing with Your Examples:
For
str = "AB57933A":- Group 1:
AB - Group 2:
57933 - Group 3:
A - Full match:
AB57933A
- Group 1:
For
str = "AB57933AbC":- Group 1:
AB - Group 2:
57933 - Group 3:
AbC - Full match:
AB57933AbC
- Group 1:
Optional: Match the Entire String
If you want to ensure the regex only matches strings that follow this exact pattern (no extra non-alphanumeric characters at the end), add a $ (end-of-string anchor) to the regex:
str.match(/^(AB)(\d+)([A-Za-z0-9]*)$/)
This way, if the string has any non-alphanumeric characters at the end (like AB57933A!), it won't match at all—only strings that are entirely AB + digits + optional alphanumerics will be captured.
内容的提问来源于stack exchange,提问作者ankur

