温馨提示×

怎么使用python正则表达式查找字符串

小亿
107
2023-08-18 04:16:37
栏目: 编程语言

使用Python的re模块来使用正则表达式查找字符串。

首先,导入re模块:

import re

然后,定义一个正则表达式模式:

pattern = r"正则表达式模式"

接下来,使用re模块的findall()函数来查找字符串:

result = re.findall(pattern, 字符串)

最后,可以打印或处理查找结果:

print(result)

以下是一个完整的示例:

import re
pattern = r"hello"
string = "hello world hello python"
result = re.findall(pattern, string)
print(result)

输出结果为:

['hello', 'hello']

注意,正则表达式模式可以根据需要进行自定义,以匹配特定的字符串模式。

0