Python正则表达式2

来自CloudWiki
跳转至: 导航搜索
import re
# 符号+的左右,前面的字符至少出现一次

line3 ="boooooobab123"
regex_str = ".*(b.+b).*"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))

#符号{1}前面的符号出现一次
line3 ="boooooobbbaab123"
regex_str = ".*(b.{1}b).*"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))

#符号{1}前面的符号出现一次以上(含一次)
line3 ="boooooobbbaab123"
regex_str = ".*(b.{1,}b).*"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))

#符号{1}前面的符号出现最少两次,最多5次
line3 ="boooooobbbaab123"
regex_str = ".*(b.{2,5}b).*"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))

#符号|代表或的关系
line3 ="bobby123"
regex_str = "(bobby|bobby123)"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))

line ="bobby123"
regex_str = "((bobby|booobby)123)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

#符合[]表示其中的任何一个
line ="boobby123"
regex_str = "([abcd]oobby123)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

#例2 验证电话号码 []中间可表示一个区间
line ="13789803458"
regex_str = "(1[48357][0-9]{9})"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

#例2 验证电话号码 []中间可表示不能是某个数
line ="13789803458"
regex_str = "(1[48357][^1]{9})"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

#\s中间出现一个空格,\S中间出现一个非空字符
line ="你 好"
regex_str = "(你\s好)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

line ="你很好"
regex_str = "(你\S好)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

line ="你很很好"
regex_str = "(你\S+好)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

#\w表示任意字符 ,包括A-Z,a-z,0-9,和下划线_
#\W表示与\w正好相反,不包含上述范围
line ="你s好"
regex_str = "(你\w好)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))

line ="你 好"
regex_str = "(你\W好)"
match_obj = re.match(regex_str,line)
if match_obj:
    print(match_obj.group(1))