Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match double quote which does not follow slash character

Tags:

java

regex

I have string like this:

"abcd\" efg\" hi" jklm"

I want to get sub string between two first characters ", which is not \" For example, in the above string, I want to get abcd\" efg\" hi Currently, I replace \" by another character, then use the regex "([^"]*)" to extract the sub string between two first characters ". Is there any way to use regex directly without replacing \" by another character.

like image 644
Waveter Avatar asked Jun 10 '16 03:06

Waveter


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.

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.

How do I not match a character in regex?

There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind. Also, a correction for you: * , ? and + do not actually match anything. They are repetition operators, and always follow a matching operator.

What do Backslashes mean in regex?

\ The backslash suppresses the special meaning of the character it precedes, and turns it into an ordinary character. To insert a backslash into your regular expression pattern, use a double backslash ('\\').


1 Answers

Use this regex:

[^\\]?"(.*?[^\\])"

Explanation:

[^\\]?   match an optional single character which is not backslash
"(.*?    match a quote followed by anything (non-greedy)
[^\\])"  match a quote preceded by anything other than backslash

This regex will match the least content between an opening quote and closing quote which does not have a backslash.

Regex101

like image 110
Tim Biegeleisen Avatar answered Oct 21 '22 22:10

Tim Biegeleisen