十七、 正则表达式– 开始、结束、贪婪和非贪婪
示例代码:
import re
# ^:以...开头:
# text = "hello world"
# search 从整个字符串中寻找需要的信息,不管位置
# result = re.search("world", text)
# result = re.search("^hello", text)
# print(result.group())
# $:以...结尾:
# text = "hello world"
# result = re.search("world$", text)
# print(result.group())
# text = ""
# result = re.search("^$", text)
# print(result.group())
# ^$可以匹配空字符
# |:匹配多个字符串或者表达式:
# text = "http"
# result = re.search("http|https|ftp", text)
# print(result.group())
# 贪婪和非贪婪:
#t ext = "12345"
# result = re.search("\d+?", text)
# result = re.search("\d+", text)
# +? 非贪婪模式,获取最少的内容
# + 贪婪模式,有多少获取多少
# print(result.group())
# 案例1:提取html标签名称:
# text = "<h1>这是标题</h1>"
# result = re.search("<.+?>", text)
# 非贪婪
# print(result.group())
# 案例2:验证一个字符是不是0-100之间的数字:
# 0,1,99,100,
# 01
text= "10"
result= re.match("0$|[1-9]|\d?$|100$", text)
print(result.group())
上一篇文章 第三章 数据解析(十六) 2019-12-27 地址:
https://www.jianshu.com/p/bbf7f7431395
下一篇文章 第三章 数据解析(十八) 2019-12-29 地址:
https://www.jianshu.com/p/a3e572078b3f
以上资料内容来源网络,仅供学习交流,侵删请私信我,谢谢。