python 正则表达式
# -*- coding: utf-8 -*- import re line = "boooooooooooooobbbaaaaby123" # ^ 以这个开始 # regex_str = "^b" 以b开始 # . 任何字符 # * 多次 regex_str = "^b.*" # 正则匹配 if re.match(regex_str, line): print('yes') # $ 结尾字符 regex_str = "^b.*3$" if re.match(regex_str, line): print('yes') # ? 非贪婪匹配 regex_str = ".*?(b.*?b).*" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # + 至少出现一次 regex_str = ".*(b.+b).*" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # {2}限定指定出现的次数 {2,}出现的次数2次以上 {2,5} 最少2次,最多5次 regex_str = ".*(b.{5,}b).*" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # | 或 line = "test123" regex_str = "((test|test456)123)" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(2)) # [] 括号内的任意一个 [0-9] [a-z] [^1] 不等与1 line = "13822345789" regex_str = "(1[3456789][^1]{9})" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # \s 空格 \S 不是空格都可以 \w 任意字符 \W 空格 line = "你 好" regex_str = "(你\W好)" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # 提取汉字 line = "hello 你好世界" regex_str = ".*?([\u4E00-\u9F45]+世界)" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # \d 数字 line = "hello 2019年" regex_str = ".*?(\d+)年" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1)) # 实例 line = "张三出生于2018年1月5日" line = "张三出生于2018/1/5" line = "张三出生于2018-1-5" line = "张三出生于2018-01-05" line = "张三出生于2018-01" regex_str = ".*?出生于(\d{4}[年/-]\d{1,2}([月/-]\d{1,2}|[月/-]$|$))" match_obj = re.match(regex_str, line) if match_obj: print(match_obj.group(1))