当前位置:脚本大全 > > 正文

python字符串匹配教程(Python字符串匹配之6种方法的使用详解)

时间:2021-10-21 07:21:58类别:脚本大全

python字符串匹配教程

Python字符串匹配之6种方法的使用详解

1. re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

  • ?
  • 1
  • 2
  • 3
  • 4
  • import re
  • line="this hdr-biz 123 model server 456"
  • pattern=r"123"
  • matchobj = re.match( pattern, line)
  • 2. re.search 扫描整个字符串并返回第一个成功的匹配。

  • ?
  • 1
  • 2
  • 3
  • 4
  • import re
  • line="this hdr-biz model server"
  • pattern=r"hdr-biz"
  • m = re.search(pattern, line)
  • 3. python 的re模块提供了re.sub用于替换字符串中的匹配项。

  • ?
  • 1
  • 2
  • 3
  • 4
  • import re
  • line="this hdr-biz model args= server"
  • patt=r'args='
  • name = re.sub(patt, "", line)
  • 4. compile 函数用于编译正则表达式,生成一个正则表达式( pattern )对象,供 match() 和 search() 这两个函数使用。

  • ?
  • 1
  • 2
  • import re
  • pattern = re.compile(r'\d+')
  • 5. re.findall 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • import re
  • line="this hdr-biz model args= server"
  • patt=r'server'
  • pattern = re.compile(patt)
  • result = pattern.findall(line)
  • 6. re.finditer 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

  • ?
  • 1
  • 2
  • 3
  • 4
  • import re
  • it = re.finditer(r"\d+","12a32bc43jf3")
  • for match in it:
  •  print (match.group() )
  • ps:python字符串匹配及正则表达式说明 

    解析url地址正则表达式:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • regexp = (r'^(?p<scheme>[a-z][\w\.\-\+]+)?:(//)?'
  •      r'(?:(?p<username>\w+):(?p<password>[\w\w]+)@|)'
  •      r'(?p<domain>[\w-]+(?:\.[\w-]+)*)(?::(?p<port>\d+))?/?'
  •      r'(?p<path>\/[\w\.\/-]+)?(?p<query>\?[\w\.*!=&@%;:/+-]+)?'
  •      r'(?p<fragment>#[\w-]+)?$')
  • match = re.search(regexp, url.strip(), re.u)
  • if match is none:
  •   raise valueerror('incorrent url: {0}'.format(url))
  • url_parts = match.groupdict()
  • url='https://blog.csdn.net/weixin_40907382/article/明细/79654372'
  • print(url_parts):{'scheme': 'https', 'username': none, 'password': none, 'domain': 'blog.csdn.net', 'port': none, 'path': '/weixin_40907382/article/明细/79654372', 'query': none, 'fragment': none}
  • 总结

    以上所述是小编给大家介绍的python字符串匹配之6种方法的使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对开心学习网网站的支持!

    原文链接:https://blog.csdn.net/qq_34500270/article/details/82899057

    上一篇下一篇

    猜您喜欢

    热门推荐