简体   繁体   中英

trying to find patterns within double quotes in python using regex

Suppose I have a string

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

Now I want to filter only the words which are in double quotes " " so the output is vijay what would be the regular expression for that?

I have tried:

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

but it didn't work.

\\"(.+?)\\" should work fine:

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

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

OUTPUT :

vijay_kapoor

EDIT :

if the intention is to further get the name before _ You may split it:

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

OUTPUT :

vijay

Don't be frustrated as a beginner. The code should work here.

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

Python demo

你可以试试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM