Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ?=. in regular expression

Tags:

I saw the phrase

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9_#@%\*\-]{8,24}$ 

in regex, which was password checking mechanism. I read few courses about regular expressions, but I never saw combination ?=. explained.

I want know how it works. In the example it is searching for at least one capital letter, one small letter and one number. I guess it's something like "if".

like image 735
Izzy Avatar asked Mar 16 '14 15:03

Izzy


People also ask

What is ?= In python regex?

(?= ...) is a positive lookahead assertion. It matches if there is the part in parentheses after ?= matches at the current position, but it will not consume any characters for the match.

How do you represent special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is the use of slash W in regex?

The combination "\w" stands for a "word" character, one of the convenience escape sequences while "\1" is one of the substitution special characters. Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself.

Which are 3 uses of regular expression?

Regular expressions are useful in any scenario that benefits from full or partial pattern matches on strings. These are some common use cases: verify the structure of strings. extract substrings form structured strings.


1 Answers

(?=regex_here) is a positive lookahead. It is a zero-width assertion, meaning that it matches a location that is followed by the regex contained within (?= and ). To quote from the linked page:

lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not. Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.

The . is not part of the lookahead, because it matches any single character that is not a line terminator.

like image 100
The Guy with The Hat Avatar answered Oct 07 '22 08:10

The Guy with The Hat