3

I need to apply multiple regular expressions on a string which I'm doing like this:

regex = re.compile("...")
regex2 = re.compile("...")
regex3 = re.compile("...")
regex4 = re.compile("...")
if regex.match(string) == None and regex2.match(string) == None and regex3.match(string) == None and regex4.match(string) == None:

I was wondering if there is another way to somehow merge or combine the single regular expressions or if I'm already doing it the 'right way'?

3
  • 1
    well, it would help if you could give sample input/output and what the regex looks like... but essentially you can combine regex expressions into one regex almost all the time. usually using | . Commented Dec 31, 2012 at 11:21
  • do you want apply different actions dependent on the match? Commented Dec 31, 2012 at 11:22
  • e.g. I have two expressions regex1 = re.compile("[0-9]+[a-zA-z0-9]*") regex2 = re.compile("[a-zA-z]*[0-9]+[a-zA-z]+[a-zA-z0-9]*"), no the match action should always be the same if the result of a match is not 'None then nothing happens Commented Dec 31, 2012 at 11:24

1 Answer 1

3
r_list = [re.compile("..."),
          re.compile("..."),
          re.compile("..."), 
          re.compile("...")]
if any(r.match(string) for r in r_list):
    # if at least one of the regex's matches do smth
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.