Matching Quote Wrapped Strings In Javascript With Regex
I need a regex for javascript for matching '{any group of chars}' <-- where that last ' is not preceeded by a \ examples: ... foo 'bar' ... => 'bar' ... foo'bar\'' ... =&g
Solution 1:
Solution 2:
Simple scenario (as in OP)
The most efficient regex (that is written in accordance with the unroll-the-loop principle) you may use here is
"[^"\\]*(?:\\[\s\S][^"\\]*)*"
See the regex demo
Details:
"
- match the first"
[^"\\]*
- 0+ chars other than"
and\
(?:\\[\s\S][^"\\]*)*
- zer or more occurrences of:\\[\s\S]
- any char ([\s\S]
) with a\
in front[^"\\]*
- 0+ chars other than"
and\
"
- a closing"
.
Usage:
// MATCHINGvar rx = /"[^"\\]*(?:\\[\s\S][^"\\]*)*"/g;
var s = ' ... foo "bar" ... goo"o"ooogle "t\\"e\\"st"[]';
var res = s.match(rx);
console.log(res);
// REPLACINGconsole.log(s.replace(rx, '<span>$&</span>'));
More advanced scenario
If there is an escaped "
before a valid match or there are \
s before a "
, the approach above won't work. You will need to match those \
s and capture the substring you need.
/(?:^|[^\\])(?:\\{2})*("[^"\\]*(?:\\[\s\S][^"\\]*)*")/g
^^^^^^^^^^^^^^^^^^^^^^ ^
See another regex demo.
Usage:
// MATCHINGvar rx = /(?:^|[^\\])(?:\\{2})*("[^"\\]*(?:\\[\s\S][^"\\]*)*")/g;
var s = ' ... \\"foo "bar" ... goo"o"ooogle "t\\"e\\"st"[]';
var m, res=[];
while (m = rx.exec(s)) {
res.push(m[1]);
}
console.log(res);
// REPLACINGconsole.log(s.replace(/((?:^|[^\\])(?:\\{2})*)("[^"\\]*(?:\\[\s\S][^"\\]*)*")/g, '$1<span>$2</span>'));
The main pattern is wrapped with capturing parentheses, and this is added at the start:
(?:^|[^\\])
- either start of string or any char but\
(?:\\{2})*
- 0+ occurrences of a double backslash.
Solution 3:
This should do it:
"(\\[\s\S]|[^"\\])*"
It's a mixture of the other answers from Wiktor and Taufik.
Post a Comment for "Matching Quote Wrapped Strings In Javascript With Regex"