-1

I am trying to match 10 digit phone numbers (that start with 2-9) that are on word boundaries (i.e. there is white space around them.) Sometimes the above phone numbers are prefixed with an +1 or 1

I would like it to still match the 10 digit phone number that follows but discard the +1 or 1 There can be multiple phone numbers in the text. Here is my regexp

\b(([+]?[1-9]{1})?([2-9][0-9]{9}))\b

https://regex101.com/r/yS1vM4/1

Shows matches. However it doesn't match for the first row of numbers and it should NOT match on the 2nd and last row:

abcd +12125551212 xyz should match starting at 212 
abcd +2125551212 xyz should NOT match (+ sign only)
abcd 2125551212 xyz  match OK!
abcd+12125551212 xyz should NOT match (no white space at start)
abcd 12125551212 xyz should match starting at 212

Thank you

anubhava
  • 761,203
  • 64
  • 569
  • 643
user603749
  • 1,638
  • 2
  • 24
  • 36

2 Answers2

1

You can probably use this regex for your examples:

/(?:(?<= [+][1-9])|(?<= [1-9])|(?<= ))([2-9][0-9]{9})\b/gi

RegEx Demo

Or else this this regex and use matched group #1:

/\s([+]?[1-9])?([2-9][0-9]{9})\b/gi

RegEx Demo 2

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This is a better one.

(?<!\S)(?:\+?1)?([2-9]\d{9})(?!\S) 

Formatted (this):

 (?<! \S )            # Look behind, whitespace or ^ 
 (?: \+? 1 )?         # Optional +1
 ( [2-9] \d{9} )      # (1), ten digit phone
 (?! \S )             # Look ahead, whitespace or $ 
Flak DiNenno
  • 2,193
  • 4
  • 30
  • 57