一、Python3正则表达式匹配
Python中re模块提供多种与正则表达式相关的操作。其中最基本的操作就是匹配。使用re模块的match()函数进行匹配,如果字符串开头匹配成功,则返回一个匹配对象,否则返回None。
import re
text = "This is a sample text"
pattern = "This.*text"
match_obj = re.match(pattern, text)
if match_obj:
print("Match found: ", match_obj.group())
else:
print("No match found")
使用re模块的search()函数进行匹配,函数在字符串中搜索匹配项。如果搜索到,则返回一个匹配对象,否则返回None。
import re
text = "This is a sample text"
pattern = "sample"
match_obj = re.search(pattern, text)
if match_obj:
print("Match found: ", match_obj.group())
else:
print("No match found")
使用re模块的findall()函数找到所有匹配的项并以列表形式返回。如果没有找到匹配,返回空列表。
import re
text = "This is a sample text with matches"
pattern = "is"
match_list = re.findall(pattern, text)
print("Match found: ", match_list)
二、Python3正则表达式r的作用
在Python中,在正则表达式字符串之前加上”r”,会将该字符串视为原始字符串,即忽略其中的转义字符。
import re
pattern = "\t"
match_obj = re.search(pattern, "This is a\t sample text with matches")
print("Match found: ", match_obj.group())
pattern = r"\t"
match_obj = re.search(pattern, "This is a\t sample text with matches")
print("Match found: ", match_obj.group())
三、Python3正则表达式匹配回车符
在Python中,除了普通字符外,还有一些特殊字符,例如:\n、\r、\t等。匹配这些特殊字符需要使用对应的转义字符。\r(回车符)也是一个特殊字符,需要使用转义字符进行匹配。
import re
pattern = r"\r"
match_obj = re.search(pattern, "This is a sample text with \rmatches")
print("Match found: ", match_obj.group())
四、Python正则表达式的作用
Python正则表达式是一种文本模式,它可以用来匹配、替换特定的文本。Python正则表达式通常用于数据处理、文本处理、爬虫、网络编程等方面。
五、Python正则表达式应用
Python正则表达式的应用非常广泛,以下是一些实际应用场景:
1、抓取HTML、XML等页面中的数据
import re import requests url = "https://www.example.com" response = requests.get(url) pattern = r"(.*)" match_obj = re.search(pattern, response.text) if match_obj: print(match_obj.group(1))
2、提取JSON数据中的特定字段
import re
import json
json_string = '{"name":"Alice", "age":25, "gender":"female"}'
pattern = r'"name":"(\w+)"'
match_obj = re.search(pattern, json_string)
if match_obj:
print(match_obj.group(1))
3、过滤不符合条件的数据
import re
pattern = r"^(\d{4})-(\d{1,2})-(\d{1,2})$"
date_list = ["2019-10-01", "2019-20-02", "2019-03-31", "2019-04-31"]
for date in date_list:
match_obj = re.search(pattern, date)
if match_obj:
print(match_obj.group())
六、Python3正则表达式教程
如果您需要更深入的学习Python正则表达式,可以参考Python官方文档中关于re模块的内容,这里提供一个链接:
https://docs.python.org/3/library/re.html
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/254735.html
微信扫一扫
支付宝扫一扫