gpt4 book ai didi

python - 匹配来自 python re 的单引号

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:35 24 4
gpt4 key购买 nike

如何匹配下面我想要的所有名字都用单引号

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+\'')

最佳答案

以下正则表达式查找所有用引号引起来的单词:

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

这里:

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

如果您只想查找以大写字母开头的单词,可以像这样修改正则表达式:

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

关于python - 匹配来自 python re 的单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9991933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com