I have a rather complex regex below but need to make one change to it and that is to skip anytime a special character is found in front. I've tried but can't figure this out myself. Help please.
My regex:
\b\d{3}[\ -]\d{2}[\ -]\d{4}\b|\b\d{2}[\ -]\d{3}[\ -]\d{4}\b|\b\d{4}[\ -]\d{2}[\ -]\d{3}\b|\b\d{9}\b|\b\d{2}[\ -]\d{2}[\ -]\d{5}\b
Example:
Currently it detects all the below values however I need it to skip if a special leading character such as $ or * is present.
123-45-6789
123 45 6789
12 34 56789
123456789
123456788
123456789
123456789-00
CodePudding user response:
You could use this regex:
(?<![\d$*])(?=(?:[ -]?\d){9}\b)\d{2,4}([ -]?)\d{2,3}\1\d{3,5}\b
It matches:
(?<![\d$*])
: a negative lookbehind to assert the preceding character is not a digit,$
or*
(?=(?:[ -]?\d){9}\b)
: a lookahead to assert there are exactly 9 digits optionally preceded by a space or-
\d{2,4}([ -]?)\d{2,3}\1\d{3,5}
: 2-4 digits, an optional space or-
, 2-3 digits, a repetition of the previous optional separator, and 3-5 digits. This ensures that there are exactly 0 or two separators, with minimum and maximum digit group sizes around them.\b
: a word break
CodePudding user response:
Have you tried negative zero-length lookahead? If you're trying to avoid astrisks, (?!\*)
, can do that. It says to find a character that is not the literal '*'
, match required, but it's not part of the end result. https://www.regular-expressions.info/lookaround.html
I assume you're trying to not match *123-45-6789
Something like:
\b(?!\*)\d{3}[- ]\d{2}[- ]\d{4}\b|\b\d{2}[- ]\d{3}[- ]\d{4}\b|\b\d{4}[- ]\d{2}[- ]\d{3}\b|\b\d{9}\b|\b\d{2}[- ]\d{2}[- ]\d{5}\b
I tested in https://regex101.com/