Dive Into Python正则表达式

[list]
[*][color=red]不贪婪的限定符 *?、+?、?? 或 {m,n}?,尽可能匹配小的文本。[/color]
[*][color=red]\S 非空字符[/color]
[*][color=red]"." 标识任意字符非换行字符,可以通过设置编译参数来包含匹配换行字符[/color]
[*][color=red](a|b|c) 要么匹配 a ,要么匹配 b ,要么匹配 c 。[/color]
[*][color=red]| A|B 表示A或者B , AB为任意的正则表达式 另外|是非贪婪的如果A匹配,则不找B[/color]
[*][color=red]松散正则表达式:忽略空白,注释 re.VERBOSE[/color]
[*]^ 匹配字符串的开始。
[*]$ 匹配字符串的结尾。
[*]\b 匹配一个单词的边界。
[*]\d 匹配任意数字。
[*]\D 非 \d,匹配任意非数字字符。
[*]\s 表示空字符
[*]\w [a-zA-Z0-9_]
[*]\W 非 \w
[*]x? 匹配一个可选的 x 字符 (换言之,它匹配 1 次或者 0 次 x 字符)。
[*]x* 匹配0次或者多次 x 字符。
[*]x+ 匹配1次或者多次 x 字符。
[*]x{n,m} 匹配 x 字符,至少 n 次,至多 m 次。
[*](x) 一般情况下表示一个记忆组 (remembered group) 。你可以利用 re.search 函数返回对象的 groups() 函数获取它的值。
[*][] 表一系列字符 [abcd] 表a,b,c,d [^a] 表示非a
[/list]

re.sub(pattern,dest,string)
re.search(pattern,string)


电话号码正则表达式([color=red]松散正则表达式[/color]):

>>> phonePattern = re.compile(r'''
# don't match beginning of string, number can start anywhere
(\d{3}) # area code is 3 digits (e.g. '800')
\D* # optional separator is any number of non-digits
(\d{3}) # trunk is 3 digits (e.g. '555')
\D* # optional separator
(\d{4}) # rest of number is 4 digits (e.g. '1212')
\D* # optional separator
(\d*) # extension is optional and can be any number of digits
$ # end of string
''', re.VERBOSE)
>>> phonePattern.search('work 1-(800) 555.1212 #1234').groups() 1
('800', '555', '1212', '1234')
>>> phonePattern.search('800-555-1212') 2
('800', '555', '1212', '')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值