读书人

python 匹配多个字符串解决思路

发布时间: 2012-05-15 14:35:29 作者: rapoo

python 匹配多个字符串
请教各位大牛,如何在python中匹配多个字符串,如在一行中匹配字符串 AAA和 BBB

我查了下re模块,似乎只有或操作,即匹配AAA和BBB的任何一个

python有类似awk一样的'/AAA/ && 'BBB''操作吗,谢谢

[解决办法]
是这样么?

Python code
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,可以用下标操作
看例子
Python code
>>> 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'>>>>
[解决办法]
探讨

其实我想要的结果是像 或 那样

Python code
line = "rwx BBB abc AAA xyzd"
pattern=re.compile(r'AAA|BBB')
print pattern.search(line) ---》 <_sre.SRE_Match object at 0xb7495bb8>

line = "AAA xyzd rwx BBB abc"
pat……

[解决办法]
Python code
>>> 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>>>
[解决办法]
Python code
>>> 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*$
[解决办法]
Python code
>>> 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'] 

读书人网 >perl python

热点推荐