在 Python 中使用正则表达式 - 几种常用模式示例
Python 有一个名为“re”(正则表达式的缩写)的内置模块,它提供对正则表达式的支持。正则表达式是模式匹配和字符串操作的强大工具。
下面是 Python 中一些常见的正则表达式操作:
- 在字符串中搜索模式:
import re
string = "Hello, world!"
pattern = "Hello"
match = re.search(pattern, string)
if match:
print("Pattern found")
else:
print("Pattern not found")Output:
Pattern found2. 替换字符串中的模式:
import re
string = "Hello, world!"
pattern = "world"
replacement = "python"
new_string = re.sub(pattern, replacement, string)
print(new_string)Output:
Hello, python!3. 使用模式拆分字符串:
import re
string = "The quick brown fox jumps over the lazy dog"
pattern = "\s+"
words = re.split(pattern, string)
print(words)
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']在这里,模式\s+匹配一个或多个空白字符。
4.匹配字符串开头的模式:
import re
string = "Hello, world!"
pattern = "^Hello"
match = re.search(pattern, string)
if match:
print("Pattern found")
else:
print("Pattern not found")Output:
Pattern found该^字符将模式锚定到字符串的开头。
这些只是可以在 Python 中使用正则表达式执行的操作的几个简单示例。正则表达式语法可能非常复杂,因此在尝试更高级的操作之前花一些时间学习基础知识是值得的。