简体   繁体   中英

How to search a string case insensitive and (R) using regular expression in a text file using Python

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM