Derek Chen
Derek Chen

Reputation: 11

Trying to use the OR option to search for two different REGEX (python)

I am currently attempting to use re.search to match either the first pattern or the second pattern. When I do run the script the error I am given is the following: TypeError: unsupported operand type(s) for |: 'str' and 'str'

This is the statement I wrote in the script:

match = re.search("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"|"[0-9]{1,2}", string)
if match is None:
    exit()

I am looking for the search to match with an input that is either something like 255.255.255.0 or an input that is a two digit number such as 24

If possible could someone point me in the right direction to solve this issue? Thanks in advance!

Upvotes: 1

Views: 56

Answers (2)

wasif
wasif

Reputation: 15498

Don't put the | in extra quotes and use a raw string:

match = re.search(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]{1,2}", string)
if match is None:
    exit()

Upvotes: 1

costaparas
costaparas

Reputation: 5237

You shouldn't have the extra double quotes within the regex itself. The regex should just be one single string.

I.e. instead of

match = re.search("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"|"[0-9]{1,2}", string)

put

match = re.search("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|[0-9]{1,2}", string)

Upvotes: 1

Related Questions