常用正则表达式函数及实例
发布时间:2023-07-17 03:39:33
正则表达式是一种用于匹配、搜索和替换文本的强大工具。在很多编程语言和编辑器中都内置了正则表达式的支持。下面是一些常用的正则表达式函数及实例。
1. match():用于检查文本是否与正则表达式匹配,并返回匹配的文本。
import re
text = "Hello, my name is John."
pattern = r"John"
result = re.match(pattern, text)
if result:
print("Match found:", result.group())
else:
print("No match found.")
输出结果:Match found: John
2. search():用于在文本中搜索与正则表达式匹配的 个结果,并返回匹配的文本。
import re
text = "Hello, my name is John."
pattern = r"John"
result = re.search(pattern, text)
if result:
print("Match found:", result.group())
else:
print("No match found.")
输出结果:Match found: John
3. findall():用于在文本中搜索与正则表达式匹配的所有结果,并返回匹配的文本列表。
import re
text = "Hello, my name is John. I am John Doe."
pattern = r"John"
result = re.findall(pattern, text)
if result:
print("Matches found:", result)
else:
print("No match found.")
输出结果:Matches found: ['John', 'John']
4. split():用于根据正则表达式将文本分割为多个部分,并返回一个分割后的文本列表。
import re
text = "Hello, my name is John. I am John Doe."
pattern = r"\."
result = re.split(pattern, text)
print("Split result:", result)
输出结果:Split result: ['Hello, my name is John', ' I am John Doe', '']
5. sub():用于根据正则表达式将文本中与之匹配的部分替换为指定的文本,并返回替换后的文本。
import re
text = "Hello, my name is John. I am John Doe."
pattern = r"John"
result = re.sub(pattern, "Tom", text)
print("Substitution result:", result)
输出结果:Substitution result: Hello, my name is Tom. I am Tom Doe.
以上只是一些常用的正则表达式函数及实例。正则表达式拥有非常强大的功能,可以通过各种特殊字符和语法进行更复杂的匹配和操作。在应用正则表达式时,需要根据具体的需求选择合适的函数和模式,并理解其匹配规则。
