几行代码入门正则表达式(python版)

几行代码入门正则表达式(python版)

__author__ ='***'

# re  reg正则

importre

line ="bobby123"

# 正则表达式贪婪匹配,从后往前

regex_str ="^b.*3$"# ^代表以什么开头,.代表任意字符,*代表前边字符可以重复任意多次,$以那个字符结尾的,量词后面直接加上一个问号?变成非贪婪匹配

ifre.match(regex_str, line):

print("yes")

#非贪婪模式的理解,贪婪模式从后往前,加?变成非贪婪模式,则从前往后匹配

line2 ="bbooooooooooobby123"

regex_str2 =".*(b.*b).*"

match_obj2 = re.match(regex_str2, line2)

ifmatch_obj2:

print(match_obj2.group(1))# 提取出第一个括号里面匹配到的东西

line3 ="boooobaaaooobbbby123"

regex_str3 =".*?(b.*?b).*"

match_obj3 = re.match(regex_str3, line3)

ifmatch_obj3:

print(match_obj3.group(1))

line4 ="abbdabcd"

regex_str4 ="(a.*?d)"

match_obj4 = re.match(regex_str4,line4)

ifmatch_obj4:

print(match_obj4.group(1))

#+

line5 ="booooobaaaoooobbbbby123"

regex_str5 =".*(b.+b).*"

match_obj5 = re.match(regex_str5,line5)

ifmatch_obj5:

print(match_obj5.group(1))

#{}

line6 ="booooobaaaoooobbbaabby123"

regex_str6 =".*(b.{2}b).*"#{2,5}最少两次,最多5次

match_obj6 = re.match(regex_str6,line6)

ifmatch_obj6:

print(match_obj6.group(1))

#|

line7 ="boobby123"

regex_str7 ="((bobby|boobby)123)"#{2,5}最少两次,最多5次

match_obj7 = re.match(regex_str7,line7)

ifmatch_obj7:

print(match_obj7.group(2))

#[]满足其中任意一个[0-9],,[^1]不是1

#\s:空格 \S:不是空格 \w==[A-Za-z0-9]

#汉字  [\u4E00-\u9FA5]+

line8 ="study in 清华大学"

regex_str8 =".*?([\u4E00-\u9FA5]+大学)"#{2,5}最少两次,最多5次

match_obj8 = re.match(regex_str8,line8)

ifmatch_obj8:

print(match_obj8.group(1))

#\d

line9 ="xxx出生于2001年"

regex_str9 =".*?(\d+)年"#{2,5}最少两次,最多5次

match_obj9 = re.match(regex_str9,line9)

ifmatch_obj9:

print(match_obj9.group(1))

#demo

#\d

line10 ="xxx出生于2001年6月1日"

line10 ="xxx出生于2001/6/1"

line10 ="xxx出生于2001-6-1"

line10 ="xxx出生于2001-06-01"

line10 ="xxx出生于2001-06"

regex_str10 =".*出生于(\d{4}[年/-]\d{1,2}([月/-]\d{1,2}|[月/-]$|$))"#{2,5}最少两次,最多5次

match_obj10 = re.match(regex_str10,line10)

ifmatch_obj10:

print(match_obj10.group(1))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • re模块手册 本模块提供了和Perl里的正则表达式类似的功能,不关是正则表达式本身还是被搜索的字符串,都可以...
    喜欢吃栗子阅读 4,060评论 0 13
  • 1.正则表达式概述 正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regula...
    TENG书阅读 893评论 0 1
  • (一)定义 正则表达式是对字符串(包括普通字符(例如,a 到 z之间的字母)和特殊字符(称为“元字符”))操作的一...
    a荷包蛋阅读 546评论 0 0
  • 我喜欢在这儿乱写点东西 因为没人看到 哈哈 微博 朋友圈 不想别人看到 我也只有情绪比较低落的时候喜欢写写 最近有...
    叶大人阅读 390评论 0 0
  • 在本节内容中作者说默认构造函数只有一个,但是和我所了解的情况不同,作者的意思是说可以把任何构造函数作为默认构造函数...
    Stroman阅读 293评论 0 0