Python中如何让正则表达式匹配排除换行符?
如何让正则表达式排除跨行匹配
问题根源在于正则中的\W会匹配换行符(换行符属于非单词字符),导致跨行场景也能匹配。要实现仅同一行匹配,可通过以下方法修改正则:
方案一:替换\W为[^\w\n]
将正则里所有的\W替换为[^\w\n],明确排除换行符,这样匹配过程中一旦遇到换行就会终止。
修改后的代码:
import re reg = re.compile(r'\b(apple)(?:[^\w\n]+\w+){0,4}?[^\w\n]+(tree|plant|garden)') print(reg.findall('my\napple tree in the garden')) # 输出 [('apple', 'tree')] print(reg.findall('apple\ntree in the garden')) # 输出 []
方案二:用负向断言限制无换行
在apple后添加(?!.*\n)断言,确保目标词和apple之间不存在换行:
import re reg = re.compile(r'\b(apple)(?!.*\n)(?:\W+\w+){0,4}?\W+(tree|plant|garden)') print(reg.findall('my\napple tree in the garden')) # 输出 [('apple', 'tree')] print(reg.findall('apple\ntree in the garden')) # 输出 []
两种方案里,方案一更贴合原正则的匹配逻辑,通过直接限制非单词字符的范围,精准避免跨行匹配。
内容的提问来源于stack exchange,提问作者lmocsi
相关产品推荐
相关产品推荐

