正则表达式适配逗号/斜杠:解决传真号码匹配失效问题
Adjusted Regex for Fax Numbers with Commas and Slashes
Hey there! The issue with your original regex is that it doesn’t include commas in the set of allowed characters for the fax number part. Let’s fix that, plus make a few tweaks for clarity and robustness.
Revised Regex
(?i)fax\s*\:\s*\+?[\d\s()/,-]*\d
Breakdown of Changes
Let’s walk through what each part does and how we adjusted it:
(?i): Keeps the case-insensitive match for "fax" (works withFax,FAX, etc.)fax\s*\:\s*: Matches "fax" followed by optional spaces, a colon, and more optional spaces (same as your original)\+?: Still allows an optional leading plus sign for international numbers[\d\s()/,-]*: This is the key update! We added commas (,) to the character class, which now accepts:- Digits (
\d) - Spaces (
\s) - Parentheses (
()) - Slashes (
/) - Commas (
,) - Hyphens (
-placed at the end to avoid being misinterpreted as a range) - The
*means zero or more of these characters (flexible for different formatting)
- Digits (
\d: Ensures the entire sequence ends with a digit (avoids matching trailing non-digit characters if present)
Testing Against Your Examples
Let’s verify it works with your target formats:
- Match:
Fax: (91-44) 7781 1234
The regex correctly handles parentheses, hyphens, and spaces in the number. - Match:
FAX: +91 44 7781 1234,2828 1111
Now accepts the comma separating multiple fax number segments, and still captures the full sequence ending with digits.
Additional Notes
- If you want to ensure there’s at least one digit in the number (to avoid empty matches), you could adjust the
*to+like so:
This requires at least one character from the class before the final digit.(?i)fax\s*\:\s*\+?[\d\s()/,-]+\d - Parentheses don’t need to be escaped inside a character class—they’re treated as literal characters there, so we removed the backslashes for readability.
内容的提问来源于stack exchange,提问作者Nitesh
相关产品推荐
相关产品推荐

