面试题答案
一键面试import re
text = 'The dog123 runs fast, but the cat456 is lazy. dog runs faster than cat'
pattern = r'\b(dog|cat)\b' # \b 匹配单词边界,(dog|cat) 匹配 dog 或 cat
matches = re.findall(pattern, text)
print(matches)
解释:
import re
:导入Python的正则表达式模块。text
定义要搜索的字符串。pattern = r'\b(dog|cat)\b'
:\b
是单词边界匹配符,确保匹配的dog
或cat
是完整单词,而不是其他单词的一部分。(dog|cat)
是一个分组,|
表示或,即匹配dog
或者cat
。
re.findall(pattern, text)
:在text
中查找所有与pattern
匹配的内容,并以列表形式返回。print(matches)
:输出匹配到的结果。