Python基础之正则表达式

Python基础之正则表达式

本节将介绍Python中正则表达式最基本的用法,正则表达式本身不做太多介绍。


Python中正则表达式的内置模块是re,最基本的用法是判断某个字符串是否符合某个表达式,分组,找出一个字符串中所有符合某个表达式的列表。

判断字符串是否符合某个表达式

可通过search()函数和match()函数来实现,不同之处是match函数是从字符串的起始字符开始判断,而search函数是从任意位置开始判断。例如:

search:

import re

# Check if a string matches a regexp
str = "www.google.com"
match = re.search('g.*e', str)
print(match)
print(match.span())
print(str[match.start():match.end()])

print()
match = re.search('ag.*e', str)
if match:
    print("Match")
else:
    print("Not match")

print()
# Search and group
match = re.search('(g.*e)\.(com)', str)
if match:
    print(match.group(1))
    print(match.group(2))
else:
    print("Not match.")

运行结果:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_11/search.py
<re.Match object; span=(4, 10), match='google'>
(4, 10)
google

Not match

google
com

Process finished with exit code 0

match:

import re

str = "www.google.com"
match = re.match("www", str)
print(match)

match = re.match("google", str)
print(match)

运行结果:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_11/match.py
<re.Match object; span=(0, 3), match='www'>
None

Process finished with exit code 0

找出字符串中所有符合某个表达式的列表

这也是一个非常有用的操作,在网络爬虫方面应用广泛。例如:

import re

str = "www.google.com, https://www.baidu.com/, www.qq.com, https://www.amazon.com"
result = re.findall('www\..*?\.com', str)
for r in result:
    print(r)

运行结果:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_11/findall.py
www.google.com
www.baidu.com
www.qq.com
www.amazon.com

Process finished with exit code 0

当然,re模块中还有其它的函数,如splitsub等,由于不太常用,这里就不过多介绍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值