Home > Enterprise >  Regex for matching string with double backlash or backlash followed by double quotes
Regex for matching string with double backlash or backlash followed by double quotes

Time:11-25

I want to create a regex that satisfies the following condition:

  • Can contain any character that is not \n and \r. Can be empty string.
  • Can contain \" and \\, but " and \ are not allowed.

Positive examples: abc d, my \"time\", D:\\willy\\wonka, foo\\\"bar.

Negative examples: my "laser", D:\willi\badehose, foo\\"bar.

I tried using positive lookbehind, but abc d is not matched and foo\\"bar is matched:

^[^\r\n]*(?<=\\)("|\\)[^\r\n]*$ 

How can I fix this? Here is the link to regex101 for ease of testing: https://regex101.com/r/I1byls/1

CodePudding user response:

You might use a pattern to exclude matching newlines, \ or " and only match \" or \\

As all the quantifiers are optional, you could also match an empty string.

^[^\r\n"\\]*(?:\\["\\][^\r\n"\\]*)*$

The pattern matches:

  • ^ Start of string
  • [^\r\n"\\]* Optionally match any char except the listed in the character class
  • (?: Non capture group to repeat as a whole
    • \\["\\] Match either \" or \\
    • [^\r\n"\\]* Optionally match any char except the listed in the character class
  • )* Close non capture group and optionally repeat
  • $ End of string

Regex demo

  • Related