.NET Regex: negate previous character for first character in string

Consider the following line

"Some" string with "quotes" and \"pre-slashed\" quotes 

Using regex, I want to find all double quotes without a slash in front of them. So I want the regex to find four matches for a sample sentence This ....

 [^\\]" 

... will find only three of them. I believe that because of the regex state machine, which first checks the command to negate the presence of a slash.

This means that I need to write a regular expression with some kind of appearance, but I don’t know how to work with these lookaheads and lookbehinds ... im not even sure what I am looking for.

The following attempt returns 6, not 4 matches ...

 "(?<!\\) 
+4
source share
3 answers
 "(?<!\\") 

This is what you are looking for

If you want to combine "Some" and "quotes", then

 (?<!\\")(?!\\")"[a-zA-Z0-9]*" 

will make

Explanation:

  • (?<!\\") - Negative look. Indicates a group that cannot match in front of your main expression
  • (?!\\") - Negative look. Indicates a group that cannot match after your main expression
  • "[a-zA-Z0-9]*" - A string to match between regular quotes

What it means is to match everything that does not come with \ "before and \" after, but is contained inside double quotes

+3
source

You almost got it, move the quote after lookbehind, for example:

 (?<!\\)" 

You can also use cases such as

 "escaped" backslash \\"string\" 

You can use an expression for this:

 (?<!\\)(?:\\\\)*" 
+1
source

Try

 (?<!\\)(?<qs>"[^"]+") 

Explanation

 <!-- (?<!\\)(?<qs>"[^"]+") Options: case insensitive Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!\\)» Match the character "\" literally «\\» Match the regular expression below and capture its match into backreference with name "qs" «(?<qs>"[^"]+")» Match the character """ literally «"» Match any character that is NOT a """ «[^"]+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match the character """ literally «"» --> 

the code

 try { if (Regex.IsMatch(subjectString, @"(?<!\\)(?<qs>""[^""]+"")", RegexOptions.IgnoreCase)) { // Successful match } else { // Match attempt failed } } catch (ArgumentException ex) { // Syntax error in the regular expression } 
0
source

All Articles