为何部分Python正则表达式函数返回匹配对象,部分却不?
Python正则表达式常用函数的返回值差异
返回匹配对象的函数
re.match、re.search、re.fullmatch这类函数执行后会返回匹配对象(match object),无法直接打印出匹配内容,必须调用match.group()方法才能获取并输出结果。
以re.search为例:
import re match = re.search(r'\d+', 'There are 123 apples') if match: print(match.group()) # Output: '123'
直接返回可打印结果的函数
re.findall、re.split、re.sub这类正则函数的返回结果可直接打印,无需额外方法调用。
以re.split为例:
import re result = re.split(r'\s+', 'Split this string by spaces') print(result) # Output: ['Split', 'this', 'string', 'by', 'spaces']
内容的提问来源于stack exchange,提问作者NBS
相关产品推荐
相关产品推荐

