2

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.

Josh Smith
  • 21
  • 1
  • 1
  • 2
  • 1
    `^` means "start of string", and `$` is "end of string". These are called "anchors". `+` means "one or more" and `*` means "zero or more" (yes, `*` can match zero characters). – Rocket Hazmat Nov 03 '14 at 20:24
  • I wouldn't mix the language _NOT_ operator with this regex. Just search using `[^a-zA-Z]`. –  Nov 03 '14 at 20:34

2 Answers2

2

* 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.

Matthew
  • 21,467
  • 5
  • 66
  • 95
2

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.

n8wrl
  • 18,771
  • 4
  • 58
  • 100