Home > Back-end >  Regex to match one of multiple strings
Regex to match one of multiple strings

Time:11-17

Need help with regex to match either of the following:

data.testID=abd.123,
data.newID=abc.123.123,
data.testcaseID=abc.1_2,
data.testid=abc.123,
data.TestCaseID=abc.1.2,

I have tried with

m = re.search("data.[test. |new]?[ID]?=(. )?[,\}]")

CodePudding user response:

You can use

m = re.search(r"data\.(?:test\w*|new)?(?:ID)?=([^,] )", text, re.I)

See the regex demo. Details:

  • data\. - data. string (note the escaped .)
  • (?:test\w*|new)? - an optional test zero or more word chars or new strings
  • (?:ID)? - an optional ID substring
  • = - a = sign
  • ([^,] ) - Group 1: one or more chars other than ,.

See a Python demo:

import re
texts = ['data.testID=abd.123,','data.newID=abc.123.123,','data.testcaseID=abc.1_2,','data.testid=abc.123,','data.TestCaseID=abc.1.2,']
rx = re.compile(r'data\.(?:test\w*|new)?(?:ID)?=([^,] )', re.I)
for text in texts:
    m = rx.search(text)
    if m:
        print(text, '=>', m.group(1))

Output:

data.testID=abd.123, => abd.123
data.newID=abc.123.123, => abc.123.123
data.testcaseID=abc.1_2, => abc.1_2
data.testid=abc.123, => abc.123
data.TestCaseID=abc.1.2, => abc.1.2
  • Related