如何匹配下面我想要的所有名字都用单引号
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/