user451555
user451555

Reputation: 308

Regex ignores second lookahead

I can't understand why second output ignores (?!B) condition and returns 201B instead of 20 x 1B?

My PHP code:

$s_1 = '20 x 1';
$s_2 = '20 x 1B';

$pattern = '/(?<=\d)[\s]*[xX][\s]*(?=\d)(?!B)/ui';

echo preg_replace($pattern, '', $s_1); // output: 201
echo preg_replace($pattern, '', $s_2); // output: 201B

Upvotes: 2

Views: 38

Answers (1)

anubhava
anubhava

Reputation: 785661

Your last negative lookahead should be nested inside (?=\d):

(?<=\d)\s*[xX]\s*(?=\d(?!B))

RegEx Demo

When (?!B) is outside as in your regex then then zero-width assertion is applied after matching x and a space. That assertion returns true because next position is a digit.

Upvotes: 2

Related Questions