Navyseal
Navyseal

Reputation: 901

Regex not behaving as expected

I have just started to learn(been two days) and write Python code.

Been trying to get a regex to work but to no avail. I do not get any result.

My regex looks like this (?<=!# )device.*\b\W and the test string is

!# 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

I am trying to read the device string. As you can see this works in the Regex editor but not sure why it doesnt work when I use the same in a Python app.

My Python code looks like this:

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

Upvotes: 1

Views: 53

Answers (1)

Jeremy McGibbon
Jeremy McGibbon

Reputation: 3785

The way you apply the flags is slightly different, in that they should be added rather than passed as multiple arguments. This method gave me the same result as the regex tester site you linked:

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

Upvotes: 1

Related Questions