Reputation: 105
I have string called "Micro(R) Windows explorer" in a text file How to search Case insensitive and (R) also match using Regular expression code is
with open(logfile) as inf:
for line in inf:
if re.search(string,line,re.IGNORECASE):
print 'found line',line
but this string "Micro(R) Windows explorer" is not accepting giving error.
Upvotes: 0
Views: 1219
Reputation: 1205
Without a regex:
with open('C:/path/to/file.txt','r') as f:
for line in f:
if 'micro(r) windows explorer' in line.lower():
print(line)
Upvotes: 1
Reputation: 336208
For a case-insensitive search, start your regex with (?i)
or compile it with the re.I
option.
To match (R)
, use the regex \(R\)
. Otherwise, the parentheses will be interpreted as regex metacharacters (meaning a capturing group), and only the string "MicroR Windows Explorer"
would be matched by it.
Together:
with open(logfile) as inf:
regex = re.compile(r"Micro\(R\) Windows Explorer", re.I)
for line in inf:
if regex.search(line):
print 'found line',line
Upvotes: 1