python regex to match whole line with a particular regex pattern

廉价感情. 提交于 2021-02-18 17:40:14

问题


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??


回答1:


Something like:

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

?




回答2:


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...



来源:https://stackoverflow.com/questions/11818023/python-regex-to-match-whole-line-with-a-particular-regex-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!