python下re模块的常用方法

末鹿安然 提交于 2020-02-23 23:00:58

1.re.search(a,b)用于在字符串b中匹配正则表达式a

#分组提取字符串
text = "apple 's price is $299, orange 's price is $199"

res = re.search(".*(\$\d+).*(\$\d+)", text)

print(res.groups())

输出结果为
(’$299’, ‘$199’)

2.re.findall(a,b)用于在字符串b中匹配正则表达式a,以列表形式返回全部符合规则的字符串

#匹配全部符合规则的字串

text = "apple 's price is $299, orange 's price is $199"

res1 = re.findall("\$\d+", text)

print(res1)

输出结果为
[’$299’, ‘$199’]

3.re.sub(a,b,c,d) a被替换字串或正则表达式,b为替换串,c为模式串,d表示替换几个符合规则的被替换字串,默认为全部替换

text = "apple 's price is $299, orange 's price is $199"

res2 = re.sub("\$\d+", "$100", text)

print(res2)

输出结果为
apple 's price is $100, orange 's price is $100

4.re.split(a,b)用于分割字符串,a为分隔符正则表表达式,b为被分割串,以列表形式返回

text = "hello$world ni hao"

res1 = re.split("[$ ]", text)

print(res1)

输出结果为
[‘hello’, ‘world’, ‘ni’, ‘hao’]

5.re.compile()用于提前编译常用正则表达式以加快运行效率,且可多行编写正则表达式,便于书写注释,示例如下

#提前编译常用正则表达式 并且加以注释
text = "the number is 20.50"
r = re.compile(r"""
                \d+  #小数点前的整数 + 表示至少一个字符
                .?  #小数点本身   ?表示小数点可有可无,匹配0或一个字符
                \d*  #小数点后的小数部分  *表示匹配0或多个字符 即小数部分可有可无
                """, re.VERBOSE)
res2 = re.search(r, text)
print(res2.group())

输出结果为
20.50

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!