Mohamad Faiz Rosdi
Mohamad Faiz Rosdi

Reputation: 21

REGEX to match 10 digits and must contain number 4

I tried to write a regex to match a 10 digits number and it must contain number 4. like:

s=['123456abc','abcisjgm','1234567895','1231231231']
for i in s:
    if re.findall(r'[4]\d{9}\b',i):
        print(i, "is valid")
    else:
        print(i, "is not valid")

Output as below,

123456abc is not valid
abcisjgm is not valid
1234567895 is not valid -----> this should be valid
1231231231 is not valid

Upvotes: 2

Views: 348

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

Another way is to check for 10 digits using a positive lookahead.

Match digits except 4, then match 4 followed by optional digits.

^(?=\d{10}$)[0-35-9]*4\d*$
  • ^ Start of string
  • (?=\d{10}$) Assert 10 digits
  • [0-35-9]* Match 0+ times a digit except 4
  • 4 Match the required 4
  • \d* Match 0+ times a digit
  • $ End of string

Regex demo | Python demo

If it can occur multiple times in a string, you might also use word boundaries \b

Example code

import re
s=['123456abc','abcisjgm','1234567895','1231231231']

for i in s:
    if re.findall(r'\b(?=\d{10}$)[0-35-9]*4\d*\b',i):
        print(i, "is valid")
    else:
        print(i, "is not valid")

Output

123456abc is not valid
abcisjgm is not valid
1234567895 is valid
1231231231 is not valid

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use the following pattern with re.search:

^(?=\d*?4)\d{10}$

See the regex demo.

  • ^ - start of string
  • (?=\d*?4) - there must be 4 after 0 or more digits, as few as possible
  • \d{10} - ten digits
  • $ - end of string.

See the Python demo:

import re

s=['123456abc','abcisjgm','1234567895','1231231231']

for i in s:
    if re.search(r'^(?=\d*?4)\d{10}$', i):
        print(i, "is valid")
    else:
        print(i, "is not valid")

Output:

123456abc is not valid
abcisjgm is not valid
1234567895 is valid
1231231231 is not valid

Upvotes: 1

Related Questions