编译正则表达式,返回一个正则表达式对象,该对象可复用。
re.compile(pattern, flags=0) # pattern:编译时用的表达式字符串 # flags:编译标志位,用于修改正则表达式匹配方式常用flags
标志含义re.S(DOTALL)使 . 匹配包括换行符在内的所有字符re.I(IGNORECASE)忽略大小写re.L(LOCALE)本地化识别匹配,影响 \w, \W, \b, \B, \s, \Sre.M(MULTILINE)多行匹配,影响^和$re.X(VERBOSE)详细模式,该模式下正则表达式可以是多行,忽略空白字符,且可以加注释re.U根据Unicode字符集解析字符,影响\w, \W, \b, \B, \d, \D, \s, \S判断目标字符串是否在字符串开始处匹配。
re.match(pattern, string, flags=0) # pattern:正则表达式对象 # string:目标字符串用法:
re.match('hel', 'hello world').group() # 'hel' re.match('hel', 'HELLO WORLD', re.I).group() # 'HEL'注意:不完全匹配,即只判断字符串开头是否匹配。可以在正则表达式对象末尾加上边界符$来实现完全匹配。
判断目标字符串是否在字符串中匹配,只要找到第一个匹配则返回,没有匹配则返回None。
re.search(pattern, string, flags=0) # pattern:正则表达式对象 # string:目标字符串用法:
re.search('wor', 'hello world').group() # wor re.search('wor', 'HELLO WORLD', re.I).group() # WOR相同:
一旦匹配成功,会返回一个match object对象,该对象包含group等方法。
re.search('wor', 'hello world').start() # 6 # 返回匹配开始处索引 re.search('wor', 'hello world').end() # 9 # 返回匹配结束处索引 re.search('wor', 'hello world').span() # (6, 9) # 返回匹配开始、结束处索引组成的元组 re.search('wor', 'hello world').group() # 'wor' # 返回整体匹配的字符串,可以一次输入多个组号(正则表达式对象需要有进行分组)不同:
match从字符串开始处匹配,开始处不匹配则匹配失败;search在字符串整体中进行匹配,只要找到一个匹配对象即返回匹配字符串。
遍历匹配,返回所有匹配的字符串组成的列表。
re.findall(pattern, string, flags=0) # pattern:正则表达式对象 # string:目标字符串用法:
re.findall('o', 'hello world') # ['o', 'o']遍历匹配,返回一个匹配结果的迭代器。
re.finditer(pattern, string, flags=0) # pattern:正则表达式对象 # string:目标字符串用法:
res = re.finditer('o', 'hello world') for i in res: print(i.group()) # o ore.finditer()函数返回结果是一个迭代器,迭代对象为match object对象。
根据匹配的字符串分割目标字符串,返回分割后结果列表。
re.split(pattern, string[, maxsplit[, flags=0]]) # pattern:正则表达式对象 # string:目标字符串 # maxsplit:最大分割次数,默认为无穷大即分割为最小块用法:
re.split('o', 'hello world') # ['hell', 'w', 'rld'] re.split('o', 'hello world', 1) # ['hell', 'world']替换给定字符串的匹配子串,返回替换后对象。
re.sub(pattern, repl, string, count) # pattern:正则表达式对象 # repl:替换对象 # string:目标字符串 # count:替换次数,默认无穷大即全部替换用法:
re.sub('o', 'p', 'hello world') # hellp world re.sub('o', 'p', 'hello world', 1) # hellp wprld返回替换后结果和次数组成的元组。
re.subn(pattern, repl, string, count=0, flags=0) # pattern:正则表达式对象 # repl:替换对象 # string:目标字符串 # count:替换次数,默认全部替换用法:
re.subn('o','p', 'hello world') # ('hellp wprld', 2) re.subn('o','p', 'hello world', 1) # ('hellp world', 1) re.subn('o','p', 'hello world', 9) # ('hellp wprld', 2)使用正则表达式进行模式匹配的时候默认都是贪婪模式,即在匹配范围内尽可能匹配最大长度的字符串。贪婪模式会影响到*、+、{m, n}等元字符的使用,可以在后面加上?使其变为非贪婪模式。
re.search('abc.*d', 'abcdccccd') # 贪婪模式,匹配整个字符串,输出 'abcdccccd' re.search('abc.*?d', 'abcdccccd') # 非贪婪模式,匹配到 abc 后面一个 d 即停止匹配,输出 'abcd'
转载于:https://www.cnblogs.com/jeemzz/p/11432718.html
相关资源:JAVA上百实例源码以及开源项目