-
-
- import re
-
- def regex():
- str = 'abcdab'
- patstr = 'ab'
-
- patobj = re.compile(patstr)
- got = patobj.match(str)
-
- got = re.match(patstr,str)
-
-
- result = re.match('ab','abcd')
- if result:
- print result.group()
- else:
- print result
-
- result = patobj.match('0abcd')
- if result:
- print result.group()
- else:
- print result, 'There is no result'
-
- result = patobj.search('0abcd')
- if result:
- print result.group()
- else:
- print result
-
- str = 'abcdab'
- result = patobj.findall(str)
- if result:
- print type(result), result
- else:
- print result
-
- result = patobj.finditer(str)
- if result:
- print type(result), result.next().group()
- else:
- print result
-
- result = patobj.sub('__','abcdab')
- if result:
- print 'replace:',result
- else:
- print result
-
- result = patobj.subn('__','abcdab')
- if result:
- print 'replace:',result
- else:
- print result
-
-
-
- str = '[1]aaaa[2]bbbb[3]cccc@1[:]dddd'
- result = re.search(r'
(\d+
(.*)@1
(.∗))
',str) - if result:
- print result.group()
- print result.group(1)
- print result.group(2)
- print result.group(3)
- print result.groups()
- else:
- print result
-
-
-
- str = '[1]aaaa[2]bbbb[3]cccc@1[:]dddd'
- result = re.search(r'
.∗
',str) - if result:
- print result.group()
- else:
- print result
-
- str = '[1]aaaa[2]bbbb[3]cccc@1[:]dddd'
- result = re.search(r'
.∗?
',str) - if result:
- print result.group()
- else:
- print result
-
-
-
-
-
- if __name__ == '__main__':
- regex()
--------------------------------------------------------补充分割线------------------------------------------------------------------------
最近用到了几个标识的参数,比如:忽略大小写,多行搜索等。这里补充一下:
有哪些标识可以使用?
- re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
- re.M(re.MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
- re.S(re.DOTALL): 点任意匹配模式,改变'.'的行为,设置后可以匹配\n
- re.L(re.LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
- re.U(re.UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
- re.X(re.VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。
哪些函数支持这些标识?
- re.compile(pat, string, flag=0)
- re.findall(pat, string, flag=0)
- re.match(pat, string, flag=0)
- re.search(pat, string, flag=0)
其中flag就是使用标识的地方,可以替换为上述的标识,如果要使用多个标识,则格式为:re.I|re.M|re.S|...
这里要注意说明的是:re.M多行只能影响^和$匹配,不会影响跨行的内容匹配,比如:
- str1 = "ab12\nbdc"
- pat1 = "^a.*2$"
- pat2 = "a.*d"
- pat3 = "^a.*c$"
- print re.match(pat1, str1)
- print `re.match(pat1, str1, re.M).group()`
-
- print re.match(pat2, str1, re.M)
-
- print `re.match(pat2, str1, re.S).group()`
- print `re.match(pat3, str1, re.S).group()`