1

I am wondering if there is a better Python Regex solution for the one that I currently have? Currently my code is:

import re

n = '+17021234567'
m = '7021234567'
match = re.search(r'(?:\+1)?(\d{10})', n)
match.group(1)

match = re.search(r'(?:\+1)?(\d{10})', m)
match.group(1)

The goal of the code is to only extract the 10 digit ph # if it has a leading +1 or not. Currently it works, but I am wondering is there a way to just call match.group() to get the 10 digit ph # without calling match.group(1)?

3 Answers 3

2

No, without the use of capturing groups, it couldn't be possible through re.match function. Since re.match tries to match the input string from the beginning. But it could be possible through re.search

>>> re.search(r'\d{10}$', n).group()
'7021234567'
>>> re.search(r'\d{10}$', m).group()
'7021234567'
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think OP meant re.match but the variable match the they used
1

you want to only capture digit use '\d' for digit

n = '+17021234567'
re.findall('\d{10}$',n)

Comments

1

use this pattern

(?<=^|\+1)\d{10}$

Demo

(?<=                    look behind to see if there is:
  ^                       the beginning of the string
 |                        OR
  \+1                     '+1'
)                        end of look-behind
\d{10}                   digits (0-9) (10 times)
$                        before an optional \n, and the end of the string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.