Reputation: 67
I am trying to match a set of strings outside paired strings with a regex expression.
There is at least one post regarding this however it is not clear to me how this works. Regex match text outside of brackets
For example, a sample string would be:
<= \( <= \) <= \( <= \) <= \( <= \)
My current regex used a lookbehind and lookahead although this does not work:
(?<=(\\\)))<=(?=(\\\())
I want to match <= which are not between \( \)
so I can replace it with &le to get:
&le \( <= \) &le \( <= \) &le \( <= \)
Note that \( \)
may or may not exist.
Upvotes: 2
Views: 232
Reputation: 849
You can use (?<!([^\\]*\\\())(<=)(?!([^\\]*\\\)))
it uses a negative lookbehind and a negative lookahead to make sure there is not a \(
behind it and not a \)
in front of it.
A negative lookahead/look behind is the same as a positive lookahead/look behind except that it checks if there is not that group instead of checking if there is.
Hopefully, this helps.
Upvotes: 0
Reputation: 370989
You'll have to use a replacer function for this. Match \(
eventually followed by \)
, OR match <=
. If the parentheses were matched, replace with the whole match (so as to keep what's inside the parentheses unchanged) - otherwise, replace the <=
match with &le
:
const input = String.raw`<= \( <= \) <= \( <= \) <= \( <= \)`;
const output = input.replace(
/\\(.*?\\)|<=/g,
match => match === '<=' ? '&le' : match
);
console.log(output);
\\(.*?\\)|<=
means match either:
\\(
- Literal backslash, followed by (
.*?
- Any characters, until encountering\\)
- Literal backslash, followed by )
OR match
<=
- the plain characters <=
(if the JS engine was more advanced, it'd be possible without a replacer function, eg \\(.*?\\)(*SKIP)(*FAIL)|<=
, but JS doesn't support that)
Be careful when using lookbehind in Javascript - only very new browsers support that. Many older browsers cannot understand it, and will throw errors. Better to avoid using lookbehind when possible, at least for the forseeable future, if you want your site to work for as many visitors as possible.
Upvotes: 1