-1

I have a file which has the following input :

xa%1bc
ba%1bc
.
.

and so on. I want to use match and regex to identify the lines which have a%1bin them. I am using

 import re
 p1 = re.compile(r'\ba%1b\b', flags=re.I)
 if re.match(p1,linefromfile):
    continue

It doesnt seem to detect the line with %1. What is the issue? Thanks

smci
  • 32,567
  • 20
  • 113
  • 146
Zzrot
  • 304
  • 2
  • 4
  • 20
  • 6
    The issue is `\b` around your pattern. It stands for "word boundary", so it wouldn't match any of your examples. Also, you don't need regex to simply check for a substring. – Lev Levitsky Sep 17 '16 at 20:23
  • 2
    There are several problems. First you should just [be using `in`](http://stackoverflow.com/questions/5319922/python-check-if-word-is-in-a-string). Second, you are checking for word boundaries where none exist. Third, you are only looking at the beginning of the string with `match` when [you need `search` to look in the whole string](http://stackoverflow.com/questions/14933771/python-regular-expression-re-match-why-this-code-does-not-work). – TigerhawkT3 Sep 17 '16 at 20:33

2 Answers2

1

match only search the pattern at the beginning of the string, if you want to find out if a string contains a pattern, use search instead. Besides you don't need the word boundary, \b:

re.search(pattern, string, flags=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

import re
if re.search(r"a%1b", "xa%1bc"):
    print("hello")
# hello
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

You can try

if 'a%1b' in linefromfile:

OR

if you need regex

if re.match('a%1b', linefromfile):
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49