您的位置:首页 > 移动开发 > Objective-C

re.MatchObject() Python

2015-12-02 11:17 615 查看
Match object对象有一个布尔值。可以通过if检查Mathch object是否匹配成功。Match object是re方法match()和seatch()返回的对象,没有匹配成功,返回None,否则True。group(),groups()方法返回Match object中的字符串:
<pre name="code" class="python">#pattern中的()用来分组 group(0)整个匹配到的match,group(1)为第一个,以此类推
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')
#groups()将分组匹配到的字符串作为元祖返回,没有匹配到的分组默认None
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # Second group defaults to None.
('24', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('24', '0')

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: