繁体   English   中英

使用正则表达式搜索不区分大小写的括号

[英]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

那么如何使用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)
# => ']'

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

编辑:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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