让我们看几个例子:
- # This checks for '' in the string instead of 't' due to the '' used
- re.search(r'Backstail', 'Backstail').group()
- 'Backstail'
- # This treats 's' as an escape character because it lacks '' at the start of 's'
- re.search(r'Backstail', 'Back tail').group()
- 'Back lash'
假如您要查找序列中的长模式,将变得很是乏味。荣幸的是,该re模块行使以下非凡字符处理赏罚一再:
- re.search(r'Co+kie', 'Cooookie').group()
- 'Cooookie'
- # Checks for any occurrence of a or o or both in the given sequence
- re.search(r'Ca*o*kie', 'Caokie').group()
- 'Caokie'
- # Checks for exactly zero or one occurrence of a or o or both in the given sequence
- re.search(r'Colou?r', 'Color').group()
- 'Color'
可是,假如您要搜查序列一再简直切数量怎么办?
譬喻,搜查应用措施中电话号码的有用性。re模块还行使以下正则表达式很好地处理赏罚了此题目:
{x} -一再x次。
{x,} -一再至少x次或更多。
{x, y} -一再至少x次,但不高出y次。
- re.search(r'd{9,10}', '0987654321').group()
- '0987654321'
将+和*资格赛被以为是greedy。
假设,当您验证电子邮件地点并想要别离搜查用户名和主机时。
这是group正则表达式成果派上用场的时辰。它应承您拾取匹配文本的一部门。
由括号()界定的正则表达式模式的部门称为groups。括号不会变动表达式匹配的内容,而是在匹配的序列内形成组。group()在本教程的示例中,您一向都在行使该成果。match.group()像泛泛一样,没有任何参数的纯文本如故是整个匹配文本。
- email_address = 'Please contact us at: support@datacamp.com'
- match = re.search(r'([w.-]+)@([w.-]+)', ____________)
- if _____:
- print(match.group()) # The whole matched text
- print(match.group(1)) # The username (group 1)
- print(match.group(2)) # The host (group 2)
贪心vs非贪心匹配
当非凡字符与搜刮序列(字符串)尽也许匹配时,则称为"贪心匹配"。这是正则表达式的正常举动,但偶然不但愿呈现这种举动:
- pattern = "cookie"
- sequence = "Cake and cookie"
- heading = r'<h1>TITLE</h1>'
- re.match(r'<.*>', heading).group()
- '<h1>TITLE</h1>'
该模式<.*>匹配整个字符串,直到第二次呈现为止>。
可是,假如只想匹配第一个
标志,则可以行使贪心的限制符*?,该限制符匹配的笔墨越少越好。
?在限制符之后添加使其以非贪心或最小的方法执行匹配;也就是说,将匹配尽也许少的字符。跑步时<.*>,您只会与角逐<h1>。
- heading = r'<h1>TITLE</h1>'
- re.match(r'<.*?>', heading).group()
- '<h1>'
re Python库
Re Python中的库提供了几个函数,使其值得把握。您已经看过个中的一些,譬喻re.search(),re.match()。让我们具体搜查一些有效的成果:
- search(pattern, string, flags=0)
行使此成果,您可以扫描给定的字符串/序列,以查找正则表达式发生匹配项的第一个位置。假如找到,则返回响应的匹配工具;不然,None假如字符串中没有位置与模式匹配,则返回。请留意,这None与在字符串中的某个点找到零长度匹配差异。
- pattern = "cookie"
- sequence = "Cake and cookie"
- re.search(pattern, sequence).group()
- 'cookie'
- match(pattern, string, flags=0)
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|