正则表达式没有按预期运行

时间:2017-09-19 03:18:10

标签: python regex

我刚开始学习(已经两天)并编写Python代码。

试图让正则表达式工作但无济于事。我没有得到任何结果。

我的正则表达式看起来像let str = "EH00011"; const len = str.length; function incrementNumberInString(s, l = len) { let [chars, nums] = [s.replace(/\d/g, ""), `${+s.replace(/\D/g, "") + 1}`]; while (chars.length + nums.length < l) { chars += "0" }; return chars + nums; }; str = incrementNumberInString(str); console.log(str); for (let i = 0; i < 100; i++) { str = incrementNumberInString(str); console.log(str); },测试字符串是

(?<=!# )device.*\b\W

https://regex101.com/r/m05Coq/1

我正在尝试读取设备字符串。正如您所看到的,这在Regex编辑器中有效但不确定当我在Python应用程序中使用它时它为什么不起作用。

我的Python代码如下所示:

!# Approved : YES
!# REASON: test
!# DEVICE: TEST1TEST2
!# ACL: <Rule No>/110 and 102/120
!# SECTION: MORI
!# REQUESTER: test1x
!# MODIFIER: test1

1 个答案:

答案 0 :(得分:1)

应用标志的方式略有不同,因为它们应该被添加而不是作为多个参数传递。这个方法给了我与你链接的正则表达式测试站点相同的结果:

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