Python regex for multiple search inputs

Viewed 133

I am trying to create a regex expression but facing some issue

test33 = "ID : 11111111   ID2 : 0  "

v = re.findall(r'ID :..|ID :.........|ID2 :..'
               , test33)
for x in v:
    print(x)
output -- ID : 1 
          ID2 : 0
required output = ID : 11111111 

Here in my search string ID can be 0 or some digits sometimes , the issue is in my regex if I m defining to check for both condition & the string ID val is in multiple still it validates for first condition only

i.e ID :.

& displays the result how can I fix it to achieve output for both ID : 11111111 or ID:0

2 Answers
re.findall("ID : \d\d\d\d\d\d\d\d")

You can match optional digits after ID and match 1 or more digits after the colon.

Note that the . matches any character and in your pattern it matches the exact amount.

\bID\d*\s*:\s*\d+
  • \bID Match ID preceded by a word boundary \b to prevent a partial match
  • \d* Match 0+ digits
  • \s*:\s* Match : between optional whitespace chars
  • \d+ Match 1+ digits

Regex demo | Python demo

import re
 
test33 = "ID : 11111111   ID2 : 0  "
v = re.findall(r'\bID\d*\s*:\s*\d+', test33)
 
print(v)

Output

['ID : 11111111', 'ID2 : 0']
Related