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 optionaltest
zero or more word chars ornew
strings(?:ID)?
- an optionalID
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