简体   繁体   中英

Can a regex '(?!^()$)' match anything?

Problem

In a very special case, my negative lookahead is an empty list:

(?!^()$)

Is there any string that matches it?

Clarification

Let's say:

(?!^()$)^(.*)$

Will it match everything?

Literally anything, beside empty string.

The regex contains 2 parts, (?!^()$) and ^(.*)$ :

  1. (?!^()$) Is a negative zero-width match for empty string. In order words, string.Empty is out.

  2. ^(.*)$ is a full match for anything except newlines 1 repeated 0 to many times, so basically anything.

Note : 1. exception new line character

(?!^()$) can be simplified to (?!^$) since () is a null group and will match at any position, all the time.

So now you're saying "match at any and every position where the start and end anchors aren't right next to one another, or in other words, we aren't at an empty string".

Therefore (?!^$) can match at every position in a string that isn't just empty or a newline .

(?!^()$)^(.*)$ is "match everywhere but at empty string" plus ^.*$ which will "match at and consume every single line, empty or not" (anchors ^ and $ have no effect in this case). So it's essentially saying "consume (at least) one or more characters in a string", which can be distilled down to simply .+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM