-2

What is the difference between "^[a-z]+$" vs "[^a-z]+$"?

"^[a-z]+$" = This one is anything that starts with letters

"[^a-z]+$" = This one is anything but letters

Can anyone confirm? If I'm wrong, can someone give me a regex for "anything that starts with letters" and "anything but letters"

Edit:

How about a regex for if I see a combination of letters and digits, that's invalid.

[^a-z0-9]+$

or is

it [^a-z]+[^0-9]+$

Thanks

learntosucceed
  • 999
  • 2
  • 10
  • 16
  • 1
    Yes, correct :) "lowercase letters" – Matjaž Mav Nov 14 '14 at 20:19
  • Don't forget the "$" anchoring the end. The first isn't just starting with lowercase letters, it's only lowercase letters from beginning to end. The second can start with anything, letters or not, but must end with at least one non-lowercase letter. – jas Nov 14 '14 at 20:26

2 Answers2

1

Square brackets in a regular expression specify a character class -- it matches all the characters in the brackets.

Outside a character class, ^ matches the beginning of the string or beginning of a line (depending on whether the m modifier is used). So the regular expression ^[a-z]+$ matches a line that is entirely letters. If you remove the $ (which matches the end of the string/line), you'll get a regexp that matches anything that starts with a letter; in that case, you also don't need the + quantifier (anything that starts with 1 or more letters also starts with 1 letter).

At the beginning of a character class, ^ inverts the class. Instead of matching all the characters in the brackets, it matches all characters that are not in the brackets. So [^a-z]+$ matches anything that ends with non-letters, because $ matches the end of the string/line. As above, you don't need the +, since anything that ends with 1 or more non-letters also ends with 1 non-letter. A regexp that matches when everything is a non-letter would be:

^[^a-z]+$

A regexp that matches when there's any non-letter in the line would be:

[^a-z]

i.e. no ^ or $ anchor.

Barmar
  • 596,455
  • 48
  • 393
  • 495
1

"^[a-zA-Z]+$" = This one is anything that starts with letters

"[^a-zA-Z]+$" = This one is anything but letters

If you want to include lower and upper letters

Tool for visualizing regular expressions: Visualizing regular expressions

Mladen Uzelac
  • 995
  • 1
  • 9
  • 14