python 匹配多个字符串
请教各位大牛,如何在python中匹配多个字符串,如在一行中匹配字符串 AAA和 BBB
我查了下re模块,似乎只有或操作,即匹配AAA和BBB的任何一个
python有类似awk一样的'/AAA/ && 'BBB''操作吗,谢谢
[解决办法]
是这样么?
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> def match(): import re line = "AAA xyzd rwx BBB abc" regexp = "(AAA)(.*?)(BBB)" r = re.search( regexp, line ) if r: print r.groups() >>> match()('AAA', ' xyzd rwx ', 'BBB')>>>
[解决办法]
可以用括号指定group,返回是个list,可以用下标操作
看例子
>>> import re>>> line = "AAA xyzd rwx BBB abc">>> res = r'(AAA).*?(BBB)'>>> m = re.findall(res,line)>>> len(m)1>>> m[0]('AAA', 'BBB')>>> m[0][0]'AAA'>>> m[0][1]'BBB'>>> type(m)<type 'list'>>>> m[('AAA', 'BBB')]>>> type(m[0])<type 'tuple'>>>>
[解决办法]
>>> import re>>> patt_A = re.compile('AAA')>>> patt_B = re.compile('BBB')>>> def match(ln):... return patt_A.search(ln) and patt_B.search(ln)>>> ln = "AAA xyzd rwx BBB abc">>> if match(ln):... print ln... AAA xyzd rwx BBB abc>>> >>> line = "rwx BBB abc AAA xyzd">>> if match(line):... print line... rwx BBB abc AAA xyzd>>>
[解决办法]
>>> patt = re.compile(r'((?=.*AAA)(?=.*BBB).*)')>>> def match(ln):... return patt.search(ln)... >>> if match(ln):... print ln... AAA xyzd rwx BBB abc>>> if match(line):... print line... rwx BBB abc AAA xyzd>>> 0*$
[解决办法]
>>> import re>>> pattern = re.compile("AAA.*BBB|BBB.*AAA")>>> pattern.findall('asdf AAA sdf BBB')5: ['AAA sdf BBB']>>> pattern.findall('asdf AA sdf BBB dffl AAA')6: ['BBB dffl AAA']