2

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]?=(.+)?[,\}]")
1
  • []s in regex work as "one of the characters inside. If you want groups, you have to use normal parentheses - (). And if you want a literal dot, you have to escape it. So more like r"data\.(test.+|new)(id|ID)=(.+)[,\}]" Commented Nov 16, 2021 at 12:14

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.