求解Python中一个正则表达式的问题
- Python code
# -*- encoding:utf-8 -*-'''Created on 2012-8-8@author: Keen'''import urlparsefrom urllib import urlopenimport reregexStr = '[0-9]+'sourceStr = "<html>123</html>"sourceStr2 = "fdasfs5a4f3as1321"print re.findall(regexStr,sourceStr2,0)print re.match(regexStr, sourceStr2,0)regexObj = re.compile(regexStr)matchObj = regexObj.match(sourceStr2)if matchObj: print matchObj.group()
上面的代码运行结果:
['5', '4', '3', '1321']
None
问题:用findall可以看到有匹配的结果,为什么用match就匹配不到结果呢?
[解决办法]
re.match要么不匹配,要么从字符串的开始就匹配上.字符串的开始不是说从newline开始,这个要注意,尤其是在多行模式的时候.
[解决办法]
带你回顾下re中的基本概念:
REobj.match(str,[pos[,endpos]]) 如果str开头与REobj匹配,返回一个MatchObj,否则为None。注意是从str开头开始匹配。
REobj.search(str,[pos[,endpos]]) 从str中搜索第一个和REobj匹配的部分。
RE_obj.findall(str) 返回str中搜索所有和REobj匹配的部分。返回一个tuple,其中元素是匹配到的字符串。
[解决办法]
- Python code
# -*- encoding:utf-8 -*-'''Created on 2012-8-8@author: Keen'''import urlparsefrom urllib import urlopenimport reregexStr = '[0-9]+'sourceStr = "<html>123</html>"sourceStr2 = "fdasfs5a4f3as1321"print re.findall(regexStr,sourceStr2,0)print re.match(regexStr, sourceStr2,0)#not matchprint re.match('[0-9]+', '123abc') , ' match ' #matchregexObj = re.compile(regexStr)matchObj = regexObj.match(sourceStr2)if matchObj: print matchObj.group()