I’m trying to work out a regex pattern to search a string for a 12 digit number. The number could have any number of other characters (but not numbers) in front or behind the one I am looking for.
So far I have /([0-9]{12})/ which finds 12 digit numbers correctly, however it also will match on a 13 digit number in the string.
the pattern should match 123456789012 on the following strings
- “rgergiu123456789012ergewrg”
- “123456789012”
- “#123456789012”
- “ergerg ergerwg erwgewrg \n rgergewrgrewg regewrge 123456789012 ergwerg”
it should match nothing on these strings:
- “123456789012000”
- “egjkrgkergr 123123456789012”
What you want are look-arounds. Something like:
A lookahead or lookbehind matches if the pattern is preceded or followed by another pattern, without consuming that pattern. So this pattern will match 12 digits only if they are not preceded or followed by more digits, without consuming the characters before and after the numbers.