"""re.search(pattern, string, flags)Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.扫描整个字符串,并返回第一个乐成的匹配的Match 对象;无满足要求的返回None"""s = "Cats are smarter than dogs"search_obj = re.search(r'(.*?) are (.*?) (.*?) ', s)# ()分组,| 或,多个匹配表达式其一匹配即可;.单个字符;*体现数目,0以及以上;?关闭贪婪模式print("search_obj = ", search_obj)# search_obj = <re.Match object; span=(0, 22), match='Cats are smarter than '>if search_obj: print("search_obj.groups() =", search_obj.groups()) # search_obj.groups() = ('Cats', 'smarter', 'than') print("search_obj.group() =", search_obj.group()) # search_obj.group() = Cats are smarter than print("search_obj.group(1) =", search_obj.group(1)) # search_obj.group(1) = Cats print("search_obj.span() =", search_obj.span()) # search_obj.span() = (0, 22)else: print("No search!")2.3 re.sub
"""re.sub(pattern, repl, string, count=0, flags=0)更换字符串中的匹配项,返回新的string- pattern:正则表达式对象- repl :更换的字符,也可以是函数- string: 要被查找的原始字符串- count:模式匹配后更换的最大次数,默认0体现更换全部的匹配- flags:代表功能标志位,扩展正则表达式的匹配"""phone = "158-2765-1234 # 手机号码"# 移除非数字内容num = re.sub(r'\D', "", phone) # \D 匹配非数字;\d匹配数字print("更换后的phone:", num)print(phone) # 158-2765-1234 # 手机号码 【即本身不改变】# repl 还可以是一个函数# If it is a callable, it's passed the Match object and must return a replacement string to be used. def double(matched): v = int(matched.group()) print(v) return str(v*2)# print(re.sub("\D+?", lambda x: x * 2, num))# TypeError: unsupported operand type(s) for *: 're.Match' and 'int'print(re.sub("\D+?", lambda x: x.group() * 2, num)) # 158--2567--9876print(re.sub(r"(\d+)", double, phone)) # double是自界说函数print("repl是函数:", num)2.4 re.compile
regex = re.compile(pattern="\w+", flags=0)# Compile a regular expression pattern, returning a Pattern object(正则表达式对象).- pattern:正则表达式对象- flags:代表功能标志位,扩展正则表达式的匹配print(regex) # re.compile('\\d+')2.5 regex.findall
def findall(pattern, string, flags=0): Return a list of all non-overlapping matches in the string. # 返回匹配到的内容列表 If one or more capturing groups are present in the pattern, return # 如果有子组,则只能获取到子组对应内容 a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. - pattern:正则表达式 - string:目标字符串 - flags:代表功能标志位,扩展正则表达式的匹配