wontonsoup
wontonsoup

Reputation: 479

How can I check if a string has 9 or more digits?

I'm trying to detect if a string has 9 or more digits. What's the best way to approach this?

I want to be able to detect a phone number inside a string like this:

Call me @ (123)123-1234

What's the best way to pull those numbers regardless of their positioning in the string?

Upvotes: 0

Views: 1560

Answers (3)

U13-Forward
U13-Forward

Reputation: 71620

Or without regex (slower for big strings):

print(sum(letter.isdigit() for letter in my_string)>=9)

Or part regex:

print(len(re.findall("[0-9]",my_string))>=9)

Just use python for checking if nine (9) or more digits.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

Since it sounds like you just want to check whether there are 9 or more digits in the string, you can use the pattern

^(\D*\d){9}

It starts at the beginning of the string, and repeats a group composed of zero or more non-digit characters, followed by a digit character. Repeat that group 9 times, and you know that the string has at least 9 digits in it.

pattern = re.compile(r'^(?:\D*\d){9}')
print(pattern.match('Call me @ (123)123-1234')) 
print(pattern.match('Call me @ (123)123-12'))

Upvotes: 3

misterflister
misterflister

Reputation: 154

#Import the regular expressions library
import re
#set our string variable equal to yours above
string = 'Call me @ (123)123-1234'
#create a list using regular expressions, of all digits in the string
a = re.findall("[0-9]",string)
#examine the list to see if its length is 9 digits or more, and print if so
if len(a) >= 9:
  print(a)

Upvotes: 0

Related Questions