Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, Difference between ^[a-zA-Z]+$ vs [a-zA-Z]* [duplicate]

Tags:

regex

I'm very new to programming and I've been told to avoid regex for now, but I find it extremely helpful.

When writing a program to check if a string only contains letters, I found on stackoverlow that both ^[a-zA-Z]+$ and [a-zA-Z]* yield the same results. I understand how [a-zA-Z] works and I understand how [A-z]is different from both of those as well, but I do not understand +$ vs ^[]* or why they yield the same result and I'm having trouble finding anything to explain it.

Here's the example I used it in:

String student = input.next();
while (!student.matches("[a-zA-Z]*")) {
   System.out.print("Invalid input. Enter name: ");
   student = input.next();
}

This is my first question here so sorry if this kind of question is frowned upon.

like image 306
Josh Smith Avatar asked Oct 24 '25 19:10

Josh Smith


2 Answers

As you know,

[a-zA-Z]

Matches a single upper or lower-case letter.

[a-zA-Z]*

matches zero or more upper- or lower-case letters in a row.

^[a-zA-Z]+$

matches a string that STARTS with one-or more upper- or lower-case letters and also ends with it. Meaning, the only thing in your string is upper- or lower-case letters.

^ and $ play more of a role when you're dealing with streams of data, using regular expressions to sift out stuff you want while ignoring the stuff you don't. That last pattern could be used to find a stream consisting of only upper and lower-case letters.

like image 83
n8wrl Avatar answered Oct 26 '25 10:10

n8wrl


* is zero or more, + is one or more.

However, there is a larger difference which is the ^ and $. In the first example, it is saying that it MUST contain only [a-zA-Z], where the string 123abc123 is not valid.

In the 2nd example, where ^ and $ are omitted, 123abc123 is valid.

like image 41
Matthew Avatar answered Oct 26 '25 10:10

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!