Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this ? operator work in regex?

Tags:

regex

^.*(?=.*[0-9]).*$

I saw this posted in someone's code. Is this a valid regex? I know the ? is supposed to make the items before it optional like abc? makes c optional. But ? is at the start of a capturing bracket. What does that mean?

like image 627
Jonas Avatar asked Feb 20 '23 18:02

Jonas


1 Answers

? alone means : OPTIONALLY match what was before.

However, (? .. ) is used for assertions...

In your case, (?= is a look-ahead assertion, meaning : match if ONLY (what's in the brackets) follows.

Reference


(?: ... )

Non-capturing parentheses. Groups the included pattern, but does not provide capturing of matching text. Somewhat more efficient than capturing parentheses.

(?> ... )

Atomic-match parentheses. First match of the parenthesized subexpression is the only one tried; if it does not lead to an overall pattern match, back up the search for a match to a position before the "(?>"

(?# ... )

Free-format comment (?# comment ).

(?= ... )

Look-ahead assertion. True if the parenthesized pattern matches at the current input position, but does not advance the input position.

(?! ... )

Negative look-ahead assertion. True if the parenthesized pattern does not match at the current input position. Does not advance the input position.

(?<= ... )

Look-behind assertion. True if the parenthesized pattern matches text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no * or + operators.)

(?<! ... )

Negative Look-behind assertion. True if the parenthesized pattern does not match text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no * or + operators.)

like image 91
Dr.Kameleon Avatar answered Feb 26 '23 18:02

Dr.Kameleon