I am not totally clear, but if I understand you correctly, you would like to detect pairs of [
and ]
angle brackets, but skip over /
and \
escaped angle brackets like \]
and /]
, correct?
So [aaa]
would be one pair, [bbb/[ccc/]ddd]
another, and [eee\[fff\]ggg]
another.
Here is how you can parse that with three regular expressions:
var str = 'Test [1st], and [2nd\\[with\\]escapes], and [3nd/[more/]escapes][4thNoSpace] text';
var re = /(\[[^\]]*\])/g;
var result = str
.replace(/([\\\/])\]/g, '$1\x01') // replace escapes with tokens
.replace(re, function(m, p1) { // process bracket pairs
return '<b>' + p1 + '</b>';
})
.replace(/(.)\x01/g, '$1\]'); // restore escapes from tokens
console.log('before: ' + str);
console.log('result: ' + result);
document.body.insertAdjacentHTML('beforeend', result);
So, this input:
Test [1st], and [2nd\[with\]escapes], and [3nd/[more/]escapes][4thNoSpace] text
...produces this output:
Test <b>[1st]</b>, and <b>[2nd\[with\]escapes]</b>, and <b>[3nd/[more/]escapes]</b><b>[4thNoSpace]</b> text
Explanation:
- the test input string has 4 angle brackets pairs, two of which have escaped brackets, one follows another without a space
- the first regex replaces escaped angle brackets with with a temporary token, so that the second regex does not trip over escaped angle brackets
- the second regex identifies proper angle bracket pairs
- the third regex restored the tokens back to the escaped angle brackets
- the resulting text adds bold tags around the angle bracket pairs to indicate proper parsing
In the future it would be helpful to specify example input strings, and expected output for each input.