我刚刚开始学习(已经两天了)并编写Python代码。
一直在尝试让正则表达式工作但无济于事。我没有得到任何结果。
我的正则表达式看起来像这样 (?<=!# )device.*\b\W
测试字符串是
!# Approved : YES
!# REASON: test
!# DEVICE: TEST1TEST2
!# ACL: <Rule No>/110 and 102/120
!# SECTION: MORI
!# REQUESTER: test1x
!# MODIFIER: test1
https://regex101.com/r/m05Coq/1
我正在尝试读取设备字符串。正如您所看到的,这在正则表达式编辑器中有效,但不知道为什么当我在 Python 应用程序中使用它时它不起作用。
我的 Python 代码如下所示:
import re
teststr = """!# Approved : YES
!# REASON: test
!# DEVICE: TEST1TEST2
!# ACL: <Rule No>/110 and 102/120
!# SECTION: MORI
!# REQUESTER: test1x
!# MODIFIER: test1"""
def test():
q = re.compile(r'(?<=!# )device.*\b\W', re.MULTILINE | re.IGNORECASE)
print(q.findall(teststr))
最佳答案
应用标志的方式略有不同,因为它们应该被添加而不是作为多个参数传递。此方法给我的结果与您链接的正则表达式测试器站点相同:
import re
teststr = """!# Approved : YES
!# REASON: test
!# DEVICE: TEST1TEST2
!# ACL: <Rule No>/110 and 102/120
!# SECTION: MORI
!# REQUESTER: test1x
!# MODIFIER: test1"""
def test():
q = re.compile(r'(?<=!# )device.*\b\W', flags=re.IGNORECASE+re.MULTILINE)
print(q.findall(teststr))
test()
关于python - 正则表达式的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46291220/