为什么要学正则表达式 - 3

在处理正字符串的时候,经常会有一些复杂规则的字符串需求,

正则表达式就是描述这些规则的公工具。

换句话说。

正则表达式就是记录文本规则的代码。

前两期我们说了相对简单的行定位符

为什么要学正则表达式 - 1

和元字符

为什么要学正则表达式 - 2

今天我们来看看正则表达式中的那些限定符

在讲限定符之前我们首先来看一下元字符\w的使用方法

元字符\w

def match_str(string):
    regex_str = 'same\wsome'  #匹配规则
    match_regex = re.match(regex_str, string)

    if match_regex:
        print('match!')
    else:
        print('not match')

if __name__ == '__main__':
    match_str('same1some')  #进行匹配的字符串
#match

\w的意思是匹配字母数字和下划线,当有多个字母数字或者下划线的时候我们再用\w就不能判断出来了,这时候就需要使用\w*了。

def match_str(string):
    regex_str = 'same\w*some'  #匹配规则
    match_regex = re.match(regex_str, string)

    if match_regex:
        print('match!')
    else:
        print('not match')

if __name__ == '__main__':
    match_str('same123456789some')  #进行匹配的字符串
#match

在上面的例子中,使用(\w*)可以匹配任意数量的数字或者字母,如果在实际开发环境中需要匹配特定的数量的数字时要怎么办呢?如需要匹配18位的身份证号呢?

这时候就需要引入今天的主角限定符了!

限定符

什么是限定符呢?

限定符用来指定正则表达式的一个给定组件必须要出现多少次才能满足匹配。有 * 或 + 或 ? 或 {n} 或 {n,} 或 {n,m} 共6种。

常见的限定符如下:

例如咱们匹配一个9位数字的QQ号:

def match_str(string):
    regex_str = '^\d{9}$'  #匹配规则
    match_regex = re.match(regex_str, string)

    if match_regex:
        print('match!')
    else:
        print('not match')

if __name__ == '__main__':
    match_str('570607808')  #进行匹配的9位QQ号
#match

例如咱们匹配一个g后面不是u的words列表。

words= ['gold', 'Google', 'Sogu', 'Guess']
regex_str = re.compile('.*g[^u]')  #‘.’匹配任意一个字符,'*'匹配0个或多个字符,g后面不是u

for s in words:
    match_obj = re.match(regex_str, s)
    if match_obj:
        print(s)
#gold
#Google

再看一组例子,咱们匹配第一位是1-5的数字,第二位是0-9的数字

patt='[1-5][0-9]'  #匹配第一位是1-5的数字,第二位是0-9的数字
list=[10,20,30,40,2,3,59,60,'aa','3aaa']
match=re.findall(patt,str(list))

if match:
  print(match)
#['10', '20', '30', '40', '59']

匹配1-9之间的数字,且这个数字只能出现3次

patt=re.compile('([1-9]{3})')  #匹配1-9之间的数字,且这个数字只能出现3次
string = '123,abc666,45d,7778,a8b9c7'
match=re.findall(patt,string)

if match:
  print(match)
#['123', '666', '777']

好了,今天分享到此结束。明天咱们继续!

发布于 1 小时前

猜你喜欢

转载自blog.csdn.net/qq_36807888/article/details/107662547