尝试在python中使用regex查找双引号中的模式

2024-04-26 00:43:55 发布

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

假设我有一根绳子

str='hello this is "vijay_kapoor" and welcome ' 

现在我只想过滤双引号中的单词" ",所以输出是vijay 它的正则表达式是什么?你知道吗

我试过:

re.search('"[a-zA-Z0-9_]*"', str').group()

但没用。你知道吗


Tags: andrehellosearchisthis单词welcome
3条回答

你可以试试这个

re.search('"[a-z]+_',str).group()[1:-1]

\"(.+?)\"应该可以正常工作:

import re
def double_quotes(text):
  matches=re.findall(r'\"(.+?)\"',text)
  return ", ".join(matches)

print(double_quotes('hello this is "vijay_kapoor" and welcome'))

输出

vijay_kapoor

编辑:

如果打算在_之前进一步获得名称,您可以拆分它:

print(double_quotes('hello this is "vijay_kapoor" and welcome, ').split('_', 1)[0])

输出

vijay

作为初学者不要灰心。代码应该在这里工作。你知道吗

import re
string='hello this is "vijay_kapoor" and welcome '
regex = re.compile(r'\x22(\w+)_')
match = regex.search(string)
print(match.group(1))

Pythondemo

相关问题 更多 >