我想从file(say D:\Test\test.txt)
中查找以下字符串的出现次数,其中XXXXXX
可以是任何数字(数字和任意长度的字母字符的组合)。
/Operator command: SUBMIT JOB=XXXXXX#JOBS
答案 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)
或此,如果我们可能需要更多约束:
(\/Operator command: SUBMIT JOB=.+?#JOBS)
# 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.
jex.im可视化正则表达式: