python 正则表达式的一些使用

关于Python正则表达式

一些符号的表示

导入模块import re

这里是一些常用的正则表达式符号
?匹配零次或一次前面的分组。
匹配零次或多次前面的分组。
+匹配一次或多次前面的分组。
{n}匹配 n 次前面的分组。
{n,}匹配 n 次或更多前面的分组。
{,m}匹配零次到 m 次前面的分组。
{n,m}匹配至少 n 次、至多 m 次前面的分组。
{n,m}?或
?或+?对前面的分组进行非贪心匹配。
^spam 意味着字符串必须以 spam 开始。

beginsWithHello = re.compile(r’^Hello’)
beginsWithHello.search(‘Hello world!’)

spam$意味着字符串必须以 spam 结束。

endsWithNumber = re.compile(r’\d$’)
endsWithNumber.search(‘Your number is 42’)
<_sre.SRE_Match object; span=(16, 17), match=‘2’>

endsWithNumber.search(‘Your number is forty two.’) == None
True

.匹配所有字符,换行符除外。
 (.)通配字符

atRegex = re.compile(r’.at’)
atRegex.findall(‘The cat in the hat sat on the flat mat.’)
[‘cat’, ‘hat’, ‘sat’, ‘lat’, ‘mat’]
和at字母一样或者比at字母多一个

(.*) 用点-星匹配所有字符

nameRegex = re.compile(r’First Name: (.) Last Name: (.)’)
mo = nameRegex.search(‘First Name: Al Last Name: Sweigart’)
mo.group(1)
‘Al’

mo.group(2)
‘Sweigart’

\d、\w 和\s 分别匹配数字、单词和空格。
\D、\W 和\S 分别匹配出数字、单词和空格外的所有字符。
[abc]匹配方括号内的任意字符(诸如 a、b 或 c)
 。
[^abc]匹配不在方括号内的任意字符。
  1. search ()
  2. findall()
    ~~ search()将返回一个 Match对象,包含被查找字符串中的“第一次”匹配的文本,而 findall()方法将返回一组
    字符串,包含被查找字符串中的所有匹配。
    贪心模式和非贪心模式区别

nongreedyRegex=re.compile(r’<.*?>’)
mo = nongreedyRegex.search(’ for dinner.>’)
mo.group()
‘《To serve man》’

greedyRegex = re.compile(r’<.*>’)
mo = greedyRegex.search(’《To serve man》 for dinner.>’)
mo.group()
‘《To serve man》 for dinner.>’

不区分大小写匹配,使用参数re.I(或者re.IGNORECASE)

打印全部的字符串内容,包括换行符(re.DOTALL)

管理复杂的正则表达式(re.VERBOSE)
(1)r’’’ … ‘’'里面没有用一个总括号扩起来

Numbertest2 = re.compile(r’’’
…: (\d{3})
…: (-)
…: (\d{3})
…: (-)
…: (\d{4})

…: ‘’’,re.VERBOSE)

Numbertest2.findall(‘Cell:445-222-9999 Work : 444-333-0000’)
Out[32]: [(‘445’, ‘-’, ‘222’, ‘-’, ‘9999’), (‘444’, ‘-’, ‘333’, ‘-’, ‘0000’)]

(2)r’’’ … ‘’'里面用一个总括号扩起来

Numbertest = re.compile(r’’’(
…: (\d{3})
…: (-)
…: (\d{3})
…: (-)
…: (\d{4})
…: )
’’’,re.VERBOSE)

: Numbertest.findall(‘Cell:445-222-9999’)
Out[26]: [(‘445-222-9999’, ‘445’, ‘-’, ‘222’, ‘-’, ‘9999’)]

组合使用re.I re.DOTALL 和 re.VERBOSE
(1)如果希望正则表达式不区分大小写,并且句点字符匹配换行,就可以这
样构造 re.compile()调用:

someRegexValue = re.compile(‘foo’, re.IGNORECASE | re.DOTALL)

(2)如果希望正则表达式不区分大小写,并且句点字符不匹配换行,就可以这
样构造 re.compile()调用:

someRegexValue = re.compile(‘foo’, re.IGNORECASE | re.DOTALL | re.VERBOSE)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值