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

那么如何使用Python搜索包含括号的字符串,-字符

4

1 回答 1

0
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)
# => ']'

事实上,re.IGNORECASE是不必要的,因为括号没有大小写。

编辑:

u = "foo\\-bar]baz"
o = re.search('[\[\]]', u) # Does this match the \ ?
print o.group(0)
# => ']'
# Behold!
于 2012-08-10T08:35:59.693 回答