匹配来自python的单引号

2024-03-29 11:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何匹配以下内容我希望所有的名字都用单引号括起来

This hasn't been much that much of a twist and turn's to 'Tom','Harry' and u know who..yes its 'rock'

如何仅在单引号中提取名称

name = re.compile(r'^\'+\w+\'')

Tags: andoftothatthis名字turnknow
3条回答

以下正则表达式查找括在引号中的所有单个单词:

In [6]: re.findall(r"'(\w+)'", s)
Out[6]: ['Tom', 'Harry', 'rock']

这里:

  • '匹配单个引号
  • \w+匹配一个或多个单词字符
  • '匹配单个引号
  • 圆括号形成一个捕获组:它们定义由findall()返回的匹配部分。

如果您只希望查找以大写字母开头的单词,可以对regex进行如下修改:

In [7]: re.findall(r"'([A-Z]\w*)'", s)
Out[7]: ['Tom', 'Harry']

在regex中,^('hat'或'care t',以及其他名称)表示“字符串的开始”(或者,给定特定选项,“行的开始”),这是您不关心的。省略它可以使regex正常工作:

>>> re.findall(r'\'+\w+\'', s)
["'Tom'", "'Harry'", "'rock'"]

其他人建议的regex可能对您想要实现的目标更好,这是解决问题的最小更改。

我建议你

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

相关问题 更多 >