Python 正则表达式匹配两个字符之间的字符

老师你好,Python 正则表达式匹配test与O_4 #1字符之间的字符,每次都是输出#2
文件内容hello.txt:
s=test_start
FUNCsfasdsdfasdfafsdfasTIfsdfsdON : O_3
FUNfdfasdTIf asON : O_4 #1
FUNCsfasdsdfasdfafsdfasTIfsdfsdON : O_3
FUNfdfasdTIf asON : O_4 #2

import re
s = open('hello.txt').read()
c = re.findall(r"test(.*)O_4", s, re.MULTILINE | re.DOTALL)
for x in c:
print(x)
import re
s = open('hello.txt').read()
c = re.findall(r"test*?(.*)O_4*?", s, re.MULTILINE | re.DOTALL)
for x in c:
print(x)
加了*?为什么没有作用?

也许可以试试抛开正则,使用split:
#!/bin/env python

fileH = open("test")

listSec1 = []
ret = []

fileContent = fileH.read()
for s in fileContent.split("test"):
listSec1.append(s)
for s in listSec1[1].split("O_4 #1"):
ret.append(s)

print ret[0]

fileH.close()
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答