正则表达式是对字符串操作的一种逻辑公式,就是用实现定义好的一些特定 字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串” 用来表达对字符串的一种过滤逻辑。
1、 正则表达式用法 (1)最常规的匹配
import re
content = "Hello 123 4567 world_This is a Regex Demo"
result = re.match("^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$",content)
print(result)
print(result.group())
print(result.span())
(2)泛匹配
import re
content = "Hello 123 4567 world_This is a Regex Demo"
result = re.match("^Hello.*Demo$",content) print(result) print(result.group())
print(result.span()) (
3)匹配目标
import re
content = "Hello 1234567 world_This is a Regex Demo"
result = re.match("^Hello\s(\d+)\sworld.*Demo$",content)
print(result)
print(result.group(1))
print(result.span())
在目标匹配中,将需要匹配的对象用()括号括起来,那么 group(1)打印出来的 就是第一个圆括号括起来的。
(4)贪婪匹配
import re
content = "Hello 1234567 world_This is a Regex Demo"
result = re.match("^Hello.*(\d+).*Demo$",content)
print(result)
print(result.group(1))
print(result.span())
这里的.*是匹配尽可能多的数据,上面这里留下一个 7 数字用于匹配
(5)非贪婪匹配
import re
content = "Hello 1234567 world_This is a Regex Demo"
result = re.match("^Hello.*?(\d+).*Demo$",content)
print(result)
print(result.group(1))
print(result.span())
.*?匹配尽可能少的字符。
(6)匹配模式
import re
content = "Hello 1234567 world_This" \ " is a Regex Demo"
result = re.match("^Hello.*?(\d+).*Demo$",content,re.S)
print(result)
print(result.group(1))
print(result.span()) 因为.不能匹配换行符,所以当有换行符时,匹配不到相应的数据,这时候得需要 在后面加一个 re.S
2、 re.search 方法 re.search 扫描整个字符串并返回第一个成功的匹配。为了匹配方便,能用 search 的就不用 match。
import re
content = "Hello 1234567 world_This is a Regex Demo Extra stings"
result = re.search("Hello.*?(\d+).*Demo",content)
print(result)
print(result.group(1))
content = """1亲爱的小课桌2悟空3粉雾海4 姐姐真漂亮5斯 芬克斯"""
result = re.search('(.*?)',content)
print(result)
print(result.group(1))
print(result.group(2))
3、 re.findall 搜索字符串,以列表形式返回全部能匹配的子串。 content = """1亲爱的小课桌2悟空3粉雾海4 姐姐真漂亮5斯 芬克斯"""
result = re.findall('(.*?)',content,re.S)
print(result)
4、 re.sub 替换字符串中每一个匹配的子串后返回替换后的字符串。
import re
content = "Hello 1234567 world_This is a Regex Demo Extra stings"
result = re.sub("\d+","",content)
print(result)
import re
content = "Hello 1234567 world_This is a Regex Demo Extra stings"
result = re.sub("\d+","replacement",content)
print(result)
content = """1亲爱的小课桌2悟空3粉雾海4 姐姐真漂亮5斯 芬克斯"""
result = re.sub('|','',content,re.S)
result1 = re.sub('|','',result,re.S)
print(result1) content = """
2悟空
3粉雾海
4 姐姐真漂亮
"""
result = re.sub('|','',content,re.S) result1 = re.sub('
|
','',result,re.S)
result2 = re.findall("(.*?)",result1,re.S)
print(result2)
5、 re.compile 将正则表达式串编译成正则对象。 content = """1亲爱的小课桌2悟空
3粉雾海
4 姐姐真漂亮
"""
partterns = re.compile("(.*?)",re.S)
items = re.findall(partterns,content)
print(items