r = re.compile(r"\B'\w+'\B")
apos = r.findall("This hasn't been much that much of a twist and turn's to 'Tom','Harry' and u know who..yes its 'rock'")
结果:
>>> apos
["'Tom'", "'Harry'", "'rock'"]
“负单词边界”(\B)阻止了类似于Rock'n'Roll的单词中的'n'的匹配。
说明:
\B # make sure that we're not at a word boundary
' # match a quote
\w+ # match one or more alphanumeric characters
' # match a quote
\B # make sure that we're not at a word boundary
以下正则表达式查找括在引号中的所有单个单词:
这里:
'
匹配单个引号\w+
匹配一个或多个单词字符'
匹配单个引号findall()
返回的匹配部分。如果您只希望查找以大写字母开头的单词,可以对regex进行如下修改:
在regex中,
^
('hat'或'care t',以及其他名称)表示“字符串的开始”(或者,给定特定选项,“行的开始”),这是您不关心的。省略它可以使regex正常工作:其他人建议的regex可能对您想要实现的目标更好,这是解决问题的最小更改。
我建议你
结果:
“负单词边界”(
\B
)阻止了类似于Rock'n'Roll
的单词中的'n'
的匹配。说明:
相关问题 更多 >
编程相关推荐