zwithouta
zwithouta

Reputation: 1571

Whats the difference between the regular expressions (?<=\s)\d(?=\s) and (?<!\S)\d(?!\S)

Why is the expression

(?<=\s)\d(?=\s)

not the same as the expression

(?<!\S)\d(?!\S)

?

Upvotes: 0

Views: 320

Answers (2)

user557597
user557597

Reputation:

 #Why is the expression
 (?<= \s )
 \d
 (?= \s )

 #not the same as the expression
 (?<! \S )
 \d
 (?! \S )

When you use a negative assertion on a negated class it will also match
at the BOS and EOS positions, whereas the positive assertion will not.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

One difference is that positive lookbehind and lookahead require those characters being looked for to exist, whereas negative lookaround does not. For example

1 2

will have 2 matches by

(?<!\S)\d(?!\S)

but no matches by

(?<=\s)\d(?=\s)

https://regex101.com/r/tjYc1o/1

(?=\s) requires the digit to be followed by a space character, so the digit will not be matched if the digit is at the end of the string, but if (?!\S) was used instead, the negative lookahead would pass, because the digit at the end of the string is not followed by a non-whitespace character.

Upvotes: 2

Related Questions