Reputation: 450
I want to check if this set of number appears in a string in an exact pattern or not:
String I want to check: \4&2096297&0
My code
a = "SCSI\DISK&VEN_MICRON&PROD_1100\4&2096297&0&000200"
print(bool(re.match(r"\4&2096297&0+", a)))
It returns False instead of true. If I try same thing on print(bool(re.match(r"hello[0-9]+", 'hello1')))
. I get true. Where am I going wrong?
Upvotes: 0
Views: 102
Reputation: 72
import re
pattern = "\4&2096297&0"
print(bool(re.search(pattern,a))) # this would print "True"
Upvotes: 1
Reputation: 106975
\4
refers to a character whose ordinal number is octal 4
rather than a literal backslash followed by a 4
. You should use a raw string literal for the variable a
instead:
a = r"SCSI\DISK&VEN_MICRON&PROD_1100\4&2096297&0&000200"
Also, instead of using r"\4&2096297&0+"
as your regex, you should use double backslashes to denote a literal backslash so that \4
would not be interpreted as a backreference:
r"\\4&2096297&0+"
And finally, instead of re.match
, you should use re.search
since re.match
matches the regex from the beginning of the string, which is not what you want.
So:
import re
a = r"SCSI\DISK&VEN_MICRON&PROD_1100\4&2096297&0&000200"
print(bool(re.search(r"\\4&2096297&0+", a)))
would output: True
Upvotes: 0