| 
                         让我们看几个例子: 
- # 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)
 
                         (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |