Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Require that quotes are escaped in a string

Tags:

regex

thanks for looking,

I've had a terrible time trying to get the right search terms for this regex question. I need to ensure that quotes are already escaped in a string, otherwise the match should fail. (Most search results for this kind of question are just pages saying you need to escape quotes or how to escape quotes.)

Valid:

This is valid
This \"is Valid
This is al\"so Valid\"

Invalid:

This i"s invalid
This i"s inv"alid

The only thing I've managed to find so far is

((?:\\"|[^"])*)

This seems to match the first part of the following, but nothing after the escaped quote

This is a \"test

Again, this should fail:

This is a \"test of " the emergency broadcast system

Thanks for any help, I hope this is even possible.

like image 919
Bung Avatar asked Jan 05 '12 17:01

Bung


1 Answers

In C#, this appears to work as you want:

string pattern = "^([^\"\\\\]*(\\\\.)?)*$";

Stripping out the escaping leaves you with:

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

which roughly translates into: start-of-string, (multi-chars-excluding-quote-or-backslash, optional-backslash-anychar)-repeated, end-of-string

It's the start-of-string and end-of-string markers which forces the match over the complete text.

like image 98
adelphus Avatar answered Sep 24 '22 12:09

adelphus