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.
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.
By using the escape character \" we are able to use double quotes to enclose a string that includes text quoted between double quotes.
Try putting a backslash ( \ ) followed by " .
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.
r"\"\[.+\]\""
). Alternatively, enclose the string in single quotes instead (r'"\[.+\]"'
).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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With