Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match double quote in python regex?

Tags:

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.

like image 273
hidemyname Avatar asked Aug 20 '15 17:08

hidemyname


People also ask

How do you match double quotes in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.

How do you handle double quotes in Python?

By using the escape character \" we are able to use double quotes to enclose a string that includes text quoted between double quotes.

How do you include a quote in regex?

Try putting a backslash ( \ ) followed by " .

How do you read a double quoted string in Python?

Method #1 : Using backslash (“\”) This is one way to solve this problem. In this, we just employ a backslash before a double quote and it is escaped.


1 Answers

  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.
like image 56
TigerhawkT3 Avatar answered Oct 01 '22 06:10

TigerhawkT3