Surya Tej
Surya Tej

Reputation: 1382

python find all matches of multiple strings in a given string using regex?

I have a string of the below pattern.

string = "'L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796'"

My requirement is for a regular expression to find all the occurrences of following patterns as below

a string starting with L

followed by a number

a hyphen

then special keywords like "OPS-AB" or "PLT" or "COM"

then a hyphen

followed by a number

ex: L3-OPS-AB-1499

I tried the below regex but it gives a partial result

regex = re.search("L\d-(OPS|RBP_|-AB|C)|(COM|PLT)-\d+",string)

my output

'COM-310'

expected output

'L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796'

Any help will be appreciated, thanks

Upvotes: 0

Views: 923

Answers (1)

Sunitha
Sunitha

Reputation: 12005

Use re.findall

>>> re.findall(r'L\d+-(?:OPS-AB|PLT|COM|RBP_C)-\d+', string)
['L3-OPS-AB-1499', 'L3-RBP_C-449', 'L2-COM-310', 'L2-PLT-16796']

Upvotes: 1

Related Questions