简体   繁体   中英

How does this ? operator work in 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?

? 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.)

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