Replace any character matches that are not reset with a backslash

I use a regular expression to replace ( in other regular expressions (or regular expressions?) With (?: To turn them into inconsistent groups. My expression assumes no structures are used (?X and looks like this:

 ( [^\\] - Not backslash character |^ - Or string beginning ) (?: [\(] - a bracket ) 

Unfortunately, this will not work if in this case there are two matches, as in this case: how((\s+can|\s+do)(\s+i)?)?

image description

With lookbehinds, the solution is easy:

 /(?<=[^\\]|^)[\(]/g 

But javascript does not support lookbehinds, so what can I do? My searches have not brought any simple universal alternative to lookbehind.

+8
javascript regex
source share
3 answers

Use lookbehind through the spread:

 function revStr(str) { return str.split('').reverse().join(''); } var rx = /[(](?=[^\\]|$)/g; var subst = ":?("; var data = "how((\\s+can|\\s+do)(\\s+i)?)?"; var res = revStr(revStr(data).replace(rx, subst)); document.getElementById("res").value = res; 
 <input id="res" /> 

Note that the regex pattern also reverses, so we can use the look instead of look-behind, and the replacement string is also canceled. This gets too complicated with longer regular expressions, but in this case it is still not unreadable.

+2
source share

One option is to do a two-pass replacement, with a token (I like unicode for this, as it is unlikely to appear elsewhere):

 var s = 'how((\\s+can|\\s+do)(\\s+i)?)?'; var token = "\u1234"; // Look for the character preceding the ( you want // to replace. We'll add the token after it. var patt1 = /([^\\])(?=\()/g; // The second pattern looks for the token and the (. // We'll replace both with the desired string. var patt2 = new RegExp(token + '\\(', 'g'); s = s.replace(patt1, "$1" + token).replace(patt2, "(?:"); console.log(s); 

https://jsfiddle.net/48e75wqz/1/

+2
source share

(Edited)

Line example

:

 how((\s+can|\s+do)(\s+i)?)? 

single line solution:

 o='how((\\s+can|\\s+do)(\\s+i)?)?'; alert(o.replace(/\\\(/g,9e9).replace(/\(/g,'(?:').replace(/90{9}/g,'\\(')) 

result:

 how(?:(?:\s+can|\s+do)(?:\s+i)?)? 

and of course it works with strings, for example, how (((\ s + \(can\) | \ s + do) (\ s + i)?)?

0
source share

All Articles