ximmyxiao
ximmyxiao

Reputation: 2811

Regular expression not return when match fail?

In regex101: When i using regular expression /.*(?!~D)/ in the string Abc~D

I think the matching will be failed in the character 'c'

and return the matching result will be 'Ab'

But in fact the actual matching result will be the Abc~D ,seems that the matching will proceeded after failed in 'c' .

Upvotes: 0

Views: 31

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

This part of the pattern .* will first match until the end of the string. Then it will assert what is on the right is not ~D, which is true because it is at the end of the string so it will match the whole string.

You could for example start at the beginning of the string ^ and repeat matching all the characters that are not followed by ~D

^(?:.(?!~D))*
  • ^ Start of string
  • (?: Non capture group
    • .(?!~D) Match any char except a newline and assert what is directly to the right is not ~D
  • )* Close group and repeat 0 or more times

See a Regex demo

If you want to take whitespace boundaries into account instead of ^, and match for example only non whitespace chars:

(?<!\S)(?:\S(?!~D))*

Regex demo

Upvotes: 1

Related Questions