正则表达式语法及常用元字符:
正则表达式有元字符及不同组合来构成,通过巧妙的构造正则表达式可以匹配任意字符串,并完成复杂的字符串处理任务。
常用的元字符有:
其中在使用反斜线时要注意:如果以‘\'开头的元字符与转义字符相同,则需要使用‘\\'或者原始字符串,在字符串前面加上字符‘r'或‘R'。原始字符串可以减少用户的输入,主要用于‘\\',主要用于正则表达式和文件路径字符串,如果字符串以一个‘\'结束,则需要多加一个斜线,以‘\\'结束。
\ :将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。例如,'n' 匹配字符 "n"。'\n' 匹配一个换行符。序列 '\\' 匹配 "\" 而 "\(" 则匹配 "("。
常用正则表达式的写法:
‘[a-zA-Z0-9]':匹配字母或数字
‘[^abc]':匹配除abc之外的字母
‘p(ython|erl)'匹配Python和perl
‘(pattern)*'匹配0次或多次
‘(pattern)+'匹配1次或多次
‘(pattern){m,n}'匹配m_n次
‘(a|b)*c'匹配0-n次a或b后面紧跟c
‘^[a-zA-Z]{1}([a-zA-Z0-9\._]){4,19}$'匹配20个字符以字母开始
‘^(\w){6,20}$'匹配6-20个单词字符
‘^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'匹配IP
‘^[a-zA-Z]+$'检查字符中只包含英文字母
‘\w+@(\w+\.)\w+$'匹配邮箱
‘[\u4e00-\u9fa5]'匹配汉字
‘^\d{18|\d{15}$'匹配身份证
‘\d{4}-\d{1,2}-\d{1,2}'匹配时间
‘^("htmlcode">
> import re > m = re.match(r'(\w+) (\w+)','Isaac Newton,physicist') > m.group(0) 'Isaac Newton' > m.group(1) 'Isaac' > m.group(2) 'Newton' > m.group(1,2) ('Isaac', 'Newton') >m=re.match(r'("htmlcode">> import re > exampleString = '''There should be one--and preferably only one--obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never never is often better than right now.''' > pattern = re.compile(r'(?<=\w\s)never(?=\s\w)') > matchResult = pattern.search(exampleString) > matchResult.span() (171, 176) > pattern = re.compile(r'(?<=\w\s)never') > matchResult = pattern.search(exampleString) > matchResult.span() (154, 159) > pattern = re.compile(r'(?:is\s)better(\sthan)') > matchResult = pattern.search(exampleString) > matchResult.span() (139, 153) > matchResult.group(0) 'is better than' > matchResult.group(1) ' than' > pattern = re.compile(r'\b(?i)n\w+\b') > index = 0 > while True: matchResult = pattern.search(exampleString,index) if not matchResult: break print(matchResult.group(0),':',matchResult.span(0)) index = matchResult.end(0) not : (90, 93) Now : (135, 138) never : (154, 159) never : (171, 176) never : (177, 182) now : (210, 213) > pattern = re.compile(r'(?<!not\s)be\b') > index = 0 > while True: matchResult = pattern.search(exampleString,index) if not matchResult: break print(matchResult.group(0),':',matchResult.span(0)) index = matchResult.end(0) be : (13, 15) > exampleString[13:20] 'be one-' > pattern = re.compile(r'(\b\w*(?P<f>\w+)(?P=f)\w*\b)') > index = 0 > while True: matchResult = pattern.search(exampleString,index) if not matchResult: break print(matchResult.group(0),':',matchResult.group(2)) index = matchResult.end(0)+1 unless : s better : t better : t > s = 'aabc abbcd abccd abbcd abcdd' > p = re.compile(r'(\b\w*(?P<f>\w+)(?P=f)\w*\b)') > p.findall(s) [('aabc', 'a'), ('abbcd', 'b'), ('abccd', 'c'), ('abbcd', 'b'), ('abcdd', 'd')]以上就是关于python正则表达式的相关内容,更多资料请查看以前的文章。