Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: +$ VS *$ VS none

Tags:

regex

In regular expressions, what is the difference between ^[a-zA-Z]+$ and ^[a-zA-Z]*$. Also would I be able to not include it at all, either with ^[a-zA-Z]$ or ^[a-zA-Z].

I looked online and it says that + matches the preceding character one or more times and * matches the preceding character zero or one times, but I have no idea what this means in this context, or at all.

like image 653
Alan Schapira Avatar asked Dec 15 '15 14:12

Alan Schapira


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What is the difference between * and *??

*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1 , eventually matching 101 . All quantifiers have a non-greedy mode: . *? , .

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

+ means 1 or more * means 0 or more

So an empty string is found by ^[a-zA-Z]*$, but not by ^[a-zA-Z]+$

^[a-zA-Z]$ means EXACTLY one letter in the ranges a-z and A-Z.

a+ is a, aa, aaa, ..., aaa...aaa, etc

a* is an empty string, a, aa, aaa, ..., aaa...aaa, etc

^a$ is only a

EDIT: you can also use ^a?$ to find 0 or 1 occurence of a, so either an empty string or a

like image 126
SubliemeSiem Avatar answered Oct 04 '22 15:10

SubliemeSiem