正则表达式的行为不符合预期

2024-05-02 11:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习(已经两天)和编写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

我正在尝试读取设备字符串。您可以在Regex编辑器中看到这一点,但不确定为什么我在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))

Tags: andno字符串代码testredevicesection
1条回答
网友
1楼 · 发布于 2024-05-02 11:52:13

应用标志的方式略有不同,因为它们应该被添加,而不是作为多个参数传递。此方法给我的结果与您链接的regex tester站点相同:

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()

相关问题 更多 >