简体   繁体   English

有没有办法在 python 中使用正则表达式找到完全匹配而不是 substring 匹配?

[英]Is there a way to find exact match and not substring match using regex in python?

given a sentence like this Sent = "ball bearing robertshaw 20" i am using a pattern "roberts|robertshaw" and would like the result to be "robertshaw" but getting only "roberts"给定这样的句子Sent = "ball bearing robertshaw 20"我正在使用模式"roberts|robertshaw"并且希望结果是"robertshaw"但只得到"roberts"

import re
sent = "ball bearing robertshaw 20"
pattrn = "roberts|robertshaw"

re.findall(pattrn,sent)

Use word boundaries:使用单词边界:

\b(?:roberts|robertshaw)\b

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM