求教一个正则表达式问题
对于字符串:56546[werwer][3434343] 5656
如果想提取出括号中的内容,我可以这样做
patten = ur'''(\[(.+)\])(\[(.+)\])'''txt = r'56546[werwer][3434343] 5656'target = re.compile(patten , re.VERBOSE)match = target.search(txt)if match: print match.group(2) print match.group(4)
patten = ur'''(\[(.+)\]){1,2}'''txt = r'56546[werwer][3434343]5656'target = re.compile(patten , re.VERBOSE)match = target.search(txt)if match: print match.group(0) print match.group(1) print match.group(2)
Type "help", "copyright", "credits" or "license" for more information.>>> import re>>> txt = r'56546[werwer][3434343] 5656'>>> patten = '\[.+?\]'>>> re.findall( patten, txt)['[werwer]', '[3434343]']
[解决办法]
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.>>> s = '56546[werwer][3434343] 5656'>>> import re>>> mat = re.findall(r'\[([^\]]+)]', s)>>> mat['werwer', '3434343']>>>