Win
Win

Reputation: 62260

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Is there a difference between ^[a-zA-Z] and [^a-zA-Z]?

When I check in C#,

Regex.IsMatch("t", "^[a-zA-Z]")  // Returns true (I think it's correct)

Regex.IsMatch("t", "[^a-zA-Z]")  // Returns false

There are a lot of web sites using [^a-zA-Z] for the alphabet. I'm not really sure which one is correct answer.

Upvotes: 30

Views: 196588

Answers (4)

The Moof
The Moof

Reputation: 804

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

Upvotes: 7

Mitch Dempsey
Mitch Dempsey

Reputation: 39899

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

Upvotes: 23

user335719
user335719

Reputation: 91

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

Upvotes: 9

tloflin
tloflin

Reputation: 4050

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

Upvotes: 74

Related Questions