Negative Lookahead with multiple conditions

Viewed 775

I need to extract $x but not $$x and '$x'.

  1. Read $$x is invalid. Please use $x.
  2. You selected '$x' value as $x.

The following Regex works for 1.

\$x(?!$)\

I used the following Alternation (|) which had obviously failed for the second string.

\$x(?!$)|\$x(?!\')\

How to check for multiple negative lookaheads?

P.S: Should be compatible with Javascript Regex.

2 Answers

The following RegEx should do the trick:

(?<!')(?<!\$)\$x(?!')

It start by checking there's no ' at the beginning and not $ in front of $x, finally not ending with '.

Edit for JavaScript:

^\$x(?!')

This will select $x at the beginning (no ') not followed by a '.

You also can simplify the regex of @revo removing the look ahead :

(^|[^'$])\$x([^']?)

Replaced by :

$1\$y$2

See demo:

Related