lvarayut
lvarayut

Reputation: 15259

Regular expression: Match only if not followed by a duplicate character

I'm highlighting all words between pipes | using /\|(.+?)\|/g, for example, |mathSign|; the mathSign will be hilighted.

However, it has some cases that we write double pipes || for another meaning as following:

 function |mathSign| (x) {
     return |((x === 0 || isNaN(x)) ? x : (x > 0 ? 1 : -1))|; 
 }

The pattern matches |((x === 0 | and | isNaN(x)) ? x : (x > 0 ? 1 : -1))| which is wrong. The right one should ignore the || in the middle.

I tried to use lookahead concept; /\|(.+?)\|(?!\|)/g in order to ignore if the pipe followed by another pipe, however, still no luck. Any help would be appreciated.

Please see my Demo in action.

Upvotes: 0

Views: 51

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Think you mean this,

\|((?:\|\||[^|])+)\|
  • \|\| - Match greedily when || appears.
  • | - OR
  • [^|] - Match any char but not of |
  • + - One or more times.

DEMO

var s = "function |mathSign| (x) {\n     return |((x === 0 || isNaN(x)) ? x : (x > 0 ? 1 : -1))|; \n }";
alert(s.match(/\|((?:\|\||[^|])+)\|/g))

Upvotes: 1

Related Questions