Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does .* do in regex?

Tags:

c#

regex

After extensive search, I am unable to find an explanation for the need to use .* in regex. For example, MSDN suggests a password regex of

@\"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})"

for length >= 6, 1+ digit and 1+ special character.

Why can't I just use:

@\"(?=.{6,})(?=(\d){1,})(?=(\W){1,})"
like image 585
Manish Avatar asked Jan 17 '14 22:01

Manish


People also ask

What is the use of * in regex?

* , returns strings beginning with any combination and any amount of characters (the first asterisk), and can end with any combination and any amount of characters (the last asterisk). This selects every single string available.

What does * represent in regex?

That's because * is a regex operator meaning zero or more occurrences of the character or subexpression that precedes it. It has nothing whatsoever to do with the $ that follows it.

What does * n in regex mean?

Allows ASCII codes to be used in regular expressions. \x n. Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, \x41 matches A .

What is the function of the asterisk (*) in regular expressions?

In regular expressions, asterisk (*) means “match zero or more of the preceding character.” To make a “wildcard” (that is, an expression that matches anything) with regular expressions, you must use '. *' (dot asterisk). This expression means, “match zero or more of any character.”


1 Answers

.* just means "0 or more of any character"

It's broken down into two parts:

  • . - a "dot" indicates any character
  • * - means "0 or more instances of the preceding regex token"

In your example above, this is important, since they want to force the password to contain a special character and a number, while still allowing all other characters. If you used \d instead of .*, for example, then that would restrict that portion of the regex to only match decimal characters (\d is shorthand for [0-9], meaning any decimal). Similarly, \W instead of .*\W would cause that portion to only match non-word characters.

A good reference containing many of these tokens for .NET can be found on the MSDN here: Regular Expression Language - Quick Reference

Also, if you're really looking to delve into regex, take a look at http://www.regular-expressions.info/. While it can sometimes be difficult to find what you're looking for on that site, it's one of the most complete and begginner-friendly regex references I've seen online.

like image 143
valverij Avatar answered Oct 05 '22 23:10

valverij