技术需求:可识别SSN并跳过WO-开头工单编号的正则表达式(用于数据掩码)
Got it, let's tackle this SSN masking regex problem where it's incorrectly targeting the number in WO-prefixed work order IDs. The core issue is that the original regex doesn't distinguish between valid SSNs and the 9-digit number following WO-, so it ends up masking both. Here's the breakdown and solution:
Problem Analysis
Your original regex \b(?!000|666|9)\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}\b correctly validates SSNs (including formats with hyphens, spaces, or no separators), but it doesn't account for WO- prefixed IDs. Since the 9-digit number after WO- fits the "no-separator SSN" pattern, the regex matches it and applies masking—exactly what we need to avoid.
Updated Regular Expression
We'll add a negative lookbehind assertion to exclude any number that follows WO-. Here's the revised regex:
(?<!WO-)\b(?!000|666|9)\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}\b
What Each Part Does
(?<!WO-): This negative lookbehind ensures the matched number is not immediately preceded byWO-, skipping work order IDs entirely.- The rest of the regex retains your original SSN validation logic:
(?!000|666|9)\d{3}: Rejects invalid first three digits (000, 666, or starting with 9)[- ]?: Matches an optional hyphen or space separator(?!00)\d{2}: Rejects middle two digits of 00[- ]?: Another optional separator(?!0000)\d{4}: Rejects last four digits of 0000\b: Ensures we match complete numbers (not partial ones)
Masking Implementation Example (JavaScript)
To apply the mask, use this replace pattern (works for all modern browsers):
const input = "WO-011493479 011493479 778-62-8144 030 72 7381 757-85-7495 149-13-7317 401318448 003 06 8815 790714615 805 14 1893"; const masked = input.replace(/(?<!WO-)\b(?!000|666|9)(\d{3})[- ]?(?!00)(\d{2})[- ]?(?!0000)(\d{4})\b/g, 'XXX-XX-XXXX'); console.log(masked);
Output:WO-011493479 XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX XXX-XX-XXXX
Notice that WO-011493479 remains unmasked, while all valid SSNs (including the standalone 011493479) are masked correctly.
Browser Compatibility
The negative lookbehind (?<!...) is supported in all major modern browsers:
- Chrome 62+
- Firefox 78+
- Safari 12.1+
- Edge 79+
This meets your requirement for cross-browser compatibility.
内容的提问来源于stack exchange,提问作者Debarshi DasGupta

