svetaketu
svetaketu

Reputation: 279

How to use OR in regular expressions

I have some strings like "abc", "def", "xyz" and they may be followed by numbers. For example: abc123 or xyz92

If I use:

re.findall("abc|def|xyz[0-9]+",text)

then it will only return xyz followed by digits, for the rest I only get the strings.

How to match all of them without doing it manually like:

re.findall("abc[0-9]+|def[0-9]+|xyz[0-9]+",text)

Upvotes: 2

Views: 535

Answers (1)

Ayush
Ayush

Reputation: 42450

Use parenthesis, along with ?: to create a non-capturing group:

(?:abc|def|xyz)[0-9]+

Regular expression visualization

Debuggex Demo

Further, if it is possible that your strings will not be followed by numbers, you should use * (0 or more), instead of + (1 or more). This way abc and abc123 will both match:

(?:abc|def|xyz)[0-9]*

Regular expression visualization

Debuggex Demo

This is your current regex:

abc|def|xyz[0-9]+

Regular expression visualization

Debuggex Demo

Upvotes: 8

Related Questions