简体   繁体   中英

Regex Look Ahead

Today for a project I was trying to make use of regular expression and learnt about groups and how to use them. I am using this site to test it.The problem is that whenever I write the following regex:

(?=\\S*\\d)

, the site gives me an error : the expression can match 0 characters and therefore can match infinitely.

while this doesn't throw any error :

(?=\\S*\\d)(\\S{6,16})

can anyone explain to me what is the meaning of the error.

Because look aheads are assertions and they don't consume any characters.

(?=\S*\d)

When you write regex like this, it checks if it contains zero or more non spaces followed by a digit. But these characters are not consumed by the regex engine. And the pointer remains at the same position.

Example

 hello123
|
This is the initial position of pointer. It the checking starts from here

hello123
|
(?=\S*\d). Here it matches \S

hello123
 |
 (?=\S*\d)

This continues till

hello123
       |
     (?=\S*\d) Now the assertion is matched. The pointer backtracks to the position from where it started looking for regex.

 hello123
|
Now you have no more pattern to match. For the second version of the regex, the matching then begins from this postion

So what is the difference with

(?=\S*\d)(\S{6,16})

Here,

  • (?=\\S*\\d) This part does the checking. I repeat again, this part doesn't consume any characters, it just checks.

  • (\\S{6,16}) This part does the consumption of characters in the input string. That is it consumes at minimum of 6 non space characters and maximum of 16 characters.

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