close

How to combine multiple regex into single one in python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to combine multiple regex into single one in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to combine multiple regex into single one in python?

  1. How to combine multiple regex into single one in python?

    To findall with an arbitrary series of REs all you have to do is concatenate the list of matches which each returns:

  2. combine multiple regex into single one in python

    To findall with an arbitrary series of REs all you have to do is concatenate the list of matches which each returns:

Method 1

You need to compile all your regex functions. Check this example:

import re
re1 = r'\d+\.\d*[L][-]\d*\s[A-Z]*[/]\d*'
re2 = '\d*[/]\d*[A-Z]*\d*\s[A-Z]*\d*[A-Z]*'
re3 = '[A-Z]*\d+[/]\d+[A-Z]\d+'
re4 = '\d+[/]\d+[A-Z]*\d+\s\d+[A-Z]\s[A-Z]*'

sentences = [string1, string2, string3, string4]
for sentence in sentences:
    generic_re = re.compile("(%s|%s|%s|%s)" % (re1, re2, re3, re4)).findall(sentence)

Method 2

To findall with an arbitrary series of REs all you have to do is concatenate the list of matches which each returns:

re_list = [
    '\d+\.\d*[L][-]\d*\s[A-Z]*[/]\d*', # re1 in question,
    ...
    '\d+[/]\d+[A-Z]*\d+\s\d+[A-z]\s[A-Z]*', # re4 in question
]

matches = []
for r in re_list:
   matches += re.findall( r, string)

For efficiency it would be better to use a list of compiled REs.

Alternatively you could join the element RE strings using

generic_re = re.compile( '|'.join( re_list) )

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read