Regex matching wrong

Viewed 28

My current regex matches the first number 703205749 because it finds the matching number inside the string, but how can I skip the number if it doesn't start with a specific number/letter.

regex = (2|7|8|1)\d{7,12}

string = 'first number 32703205749, second number 714525596'

Should match only 714525596

1 Answers

You may use starting ^ and ending $ anchors to denote the bounds of the number. Also, your alternation of starting first digits might be easier to read as a character class. Putting all this together we can try:

^[2781]\d{7,12}$

Or, if you want to match the entire number inside a larger string, surround it by word boundaries:

\b[2781]\d{7,12}\b
Related