hidemyname
hidemyname

Reputation: 4287

How to match double quote in python regex?

I use this statement result=re.match(r"\[.+\]",sentence) to match sentence="[balabala]". But I always get None. Why? I tried many times and online regex test shows it works.

Upvotes: 5

Views: 38441

Answers (2)

Akhil Nadh PC
Akhil Nadh PC

Reputation: 614

Regx

["][\w\s]+["]

This will match any words enclosed within duble quotes, for example "asd"

s='hello dear "Akhil", how are you?'
print(re.findall(r'["][\w\s]+["]',s)

This will return "Akhil" in a list type.

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

  1. Those double-quotes in your regular expression are delimiting the string rather than part of the regular expression. If you want them to be part of the actual expression, you'll need to add more, and escape them with a backslash (r"\"\[.+\]\""). Alternatively, enclose the string in single quotes instead (r'"\[.+\]"').
  2. re.match() only produces a match if the expression is found at the beginning of the string. Since, in your example, there is a double quote character at the beginning of the string, and the regular expression doesn't include a double quote, it does not produce a match. Try re.search() or re.findall() instead.

Upvotes: 9

Related Questions