正则表达式是一种用于匹配文本模式的工具,它可以在字符串中找到符合特定规则的子串。在 Python 中,可以使用 re 模块来操作正则表达式。
以下是一些常用的正则表达式元字符和语法:
- . 代表任意单个字符,除了换行符。
-
- 代表前面的字符可以出现 0 次或多次。
-
- 代表前面的字符可以出现 1 次或多次。
- ? 代表前面的字符可以出现 0 次或 1 次。
- \d 代表任意数字,等价于 [0-9]。
- \s 代表任意空白字符,包括空格、制表符、换行符等。
- \w 代表任意字母数字字符,等价于 [a-zA-Z0-9]。
- [] 代表字符集,匹配其中任意一个字符。
- [^] 代表取反后的字符集,匹配除了其中任意一个字符以外的字符。
- () 代表分组,可以对其内部的内容进行捕获或操作。
- | 代表逻辑或,可以匹配多个模式之一。
- ^ 代表匹配字符串开头。
- $ 代表匹配字符串结尾。
- {n} 代表前面的字符必须出现 n 次。
- {n,} 代表前面的字符必须出现至少 n 次。
- {n,m} 代表前面的字符必须出现 n 到 m 次。
使用 re 模块可以对字符串进行匹配和替换操作。其中常用的方法包括:
- re.search(pattern, string):在字符串中搜索匹配 pattern 的第一个子串,并返回 MatchObject 对象。
- re.match(pattern, string):在字符串开头匹配 pattern,如果匹配成功则返回 MatchObject 对象,否则返回 None。
- re.findall(pattern, string):返回所有匹配 pattern 的子串列表。
- re.sub(pattern, repl, string):使用 repl 替换所有匹配 pattern 的子串,并返回替换后的新字符串。
需要注意的是,在处理大量数据或复杂模式时,正则表达式可能会导致性能问题。此时可以考虑使用其他更高效的字符串处理方法。
以下是一些常见的 Python 正则表达式代码演示:
1.匹配字符串中的数字
import re
text = "Your order number is 123456"
pattern = r'\d+'
result = re.search(pattern, text)
if result:
print(result.group()) # 输出:123456
2.匹配邮箱地址
import re
email = "example@gmail.com"
pattern = r'^\w+@\w+\.\w+$'
result = re.match(pattern, email)
if result:
print("Valid email address")
else:
print("Invalid email address")
3.查找所有匹配子串
import re
text = "The quick brown fox jumps over the lazy dog"
pattern = r'\b\w{3}\b' # 查找长度为 3 的单词
matches = re.findall(pattern, text)
print(matches) # 输出:['The', 'fox', 'the', 'dog']
4.替换字符串中的子串
import re
text = "Hello, world! How are you today?"
pattern = r'(\b\w{3}\b)'
new_text = re.sub(pattern, r'[**\g<1>**]', text)
print(new_text) # 输出:[**Hel**]lo, [**wor**]ld! [**How**] [**are**] [**you**] [**tod**]ay?
上述代码仅作为示例,实际使用时需要根据具体需求进行修改。