怎样在python中使用正则表达式
在Python中,我们可以使用内置的 re 模块来使用正则表达式。在这里,我将介绍一些常用的正则表达式方法和语法。
1. re.compile()
正则表达式需要编译为模式对象(pattern object)才能在程序中使用。我们可以使用re.compile()方法将正则表达式编译为模式对象:
import re
pattern = re.compile(r'\d+')
这里使用的是原始字符串(raw string)r'\d+',因为反斜杠在正则表达式中有特殊含义,所以在字符串前面加上 r 确保反斜杠被当作字面值而不是转义字符。
2. re.match()
re.match()方法用于从字符串的开头匹配正则表达式,如果匹配成功返回一个 Match 对象,否则返回 None:
import re
pattern = re.compile(r'\d+')
match = pattern.match('1234')
if match:
print(match.group())
输出为:1234
group()方法返回匹配到的字符串。
3. re.search()
re.search()方法在字符串中搜索匹配正则表达式的 个位置,如果匹配成功返回一个 Match 对象,否则返回 None:
import re
pattern = re.compile(r'\d+')
match = pattern.search('hello1234world')
if match:
print(match.group())
输出为:1234
4. re.findall()
re.findall()方法在字符串中搜索匹配正则表达式的所有子串,并返回一个列表:
import re
pattern = re.compile(r'\d+')
match = pattern.findall('hello1234world5678')
print(match)
输出为:['1234', '5678']
5. 正则表达式语法
正则表达式语法非常丰富,下面列举一些常用的语法:
(1)字符集 [] 表示一组字符中任意一个字符都可以匹配。例如,[abc] 匹配 a、b 或 c,[0-9] 匹配数字 0 到 9:
pattern = re.compile(r'[abc]')
match = pattern.search('helloabcworld')
if match:
print(match.group())
输出为:a
(2)反义字符集 [^] 表示不在一组字符中的任意一个字符都可以匹配:
pattern = re.compile(r'[^a-z]')
match = pattern.search('hello123world')
if match:
print(match.group())
输出为:1
(3)通配符 . 表示匹配任意一个字符:
pattern = re.compile(r'.ello')
match = pattern.search('hello')
if match:
print(match.group())
输出为:hello
(4)重复符 * 表示匹配前面的字符 0 次或多次,+ 表示匹配前面的字符 1 次或多次,? 表示匹配前面的字符 0 次或 1 次。例如,a* 匹配连续的任意个数的 a:
pattern = re.compile(r'a*')
match = pattern.search('hellooo')
if match:
print(match.group())
输出为:''(空字符串)
(5)定位符 ^ 和 $ 分别表示字符串的开头和结尾,例如,^hello 表示以 hello 开头的字符串,world$ 表示以 world 结尾的字符串:
pattern = re.compile(r'^hello')
match = pattern.search('hello world')
if match:
print(match.group())
输出为:hello
6. re.sub()
re.sub()方法用于替换字符串中匹配正则表达式的子串。语法如下:
re.sub(pattern, repl, string, count=0)
其中,pattern 是要匹配的正则表达式,repl 是替换的字符串或函数,string 是被替换的原始字符串,count 是替换次数,缺省值表示全部替换。
例如,下面的代码将正整数加 1:
import re
def add_one(match):
num = int(match.group())
return str(num+1)
pattern = re.compile(r'\d+')
s = '123 456 789'
result = pattern.sub(add_one, s)
print(result)
输出为:124 457 790
这里 add_one 函数接受一个 Match 对象作为参数,并通过 group() 方法获取匹配到的字符串,将其转为整数加 1,再转为字符串返回。最后,使用 pattern.sub() 方法将匹配到的字符串替换成 add_one 函数的返回值。
以上就是 Python 中正则表达式的基本用法,更多关于 re 模块的内容可以参考 Python 文档。
