简体   繁体   中英

Search for brackets in a case insensitive using regular expressions

with open(logfile) as inf:
    for line in inf:
        if re.search(string,line,re.IGNORECASE):
            print 'found line',line

So how to search string contains brackets,- characters using Python

import re

s = "foo[bar]baz"
m = re.search("[\[\]]", s)
print m.group(0)
# => '['

t = "foo-bar]baz"
n = re.search("[\[\]]", t)
print n.group(0)
# => ']'

In fact, re.IGNORECASE is unnecessary since bracktes have no case.

Edit:

u = "foo\\-bar]baz"
o = re.search('[\[\]]', u) # Does this match the \ ?
print o.group(0)
# => ']'
# Behold!

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