我想从与给定模式匹配的文件中获取行

时间:2019-06-09 18:18:07

标签: regex python-3.x

我想从file(say D:\Test\test.txt)中查找以下字符串的出现次数,其中XXXXXX可以是任何数字(数字和任意长度的字母字符的组合)。

/Operator command: SUBMIT JOB=XXXXXX#JOBS

2 个答案:

答案 0 :(得分:0)

您非常接近。您可以使用.点来匹配任何字符,添加*?惰性量词并包含#JOBS文字:

import re

file_content = """
/Operator command: SUBMIT JOB=job1#JOBS
something something
 blah blah /Operator command: SUBMIT JOB=job2#JOBS
 foobar
"""

matches = re.findall(r"/Operator command: SUBMIT JOB=.*?#JOBS", file_content)  

print(len(matches)) # => 2

如果您的.*?可能是多行,请将dotall re.S标志添加到findall调用中。

答案 1 :(得分:0)

带有一个简单捕获组的表达式可以做到这一点:

(\/Operator command:.+?#JOBS)

Demo 1

或此,如果我们可能需要更多约束:

(\/Operator command: SUBMIT JOB=.+?#JOBS)

Demo 2

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(\/Operator command:.+?#JOBS)"

test_str = ("/Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue \n\n\n"
    "/Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue /Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue \n"
    "/Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue \n\n"
    "/Operator command: SUBMIT JOB=XXXXXX#JOBS Anything we wish after and continue ")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx电路

jex.im可视化正则表达式:

enter image description here