dusual
dusual

Reputation: 2207

python regex to match whole line with a particular regex pattern

I have a file with a list of regex patterns and string containing '\n's' i.e a string with seperate lines ... I need a generic regex that can match the whole line with patterns in the regex file such that i can do something like

re.compile(r'generic_regex%s') %regex_pattern from file and it automatically matches the whole line much like grep.

Any ideas??

Upvotes: 3

Views: 5888

Answers (2)

Jon Clements
Jon Clements

Reputation: 142126

Adjust for any boundaries etc...

import re
import mmap

def find_re(fname, rx): # rx is a compiled re object
    with open(fname) as fin:
        mm = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
        return rx.findall(mm)

Shoud be fast for just sequential access... re-work the regex if needs be to go over multiple lines...

Upvotes: 0

jsbueno
jsbueno

Reputation: 110208

Something like:

>>> re.findall(r"(^.*?%s.*?$)" %expression, text, re.MULTILINE)

?

Upvotes: 8

Related Questions