user2956406
user2956406

Reputation: 177

regular expression allow point and Latin letters

I have regular expression allow only point and Latin letters. But this expression miss string where exist space. In my code I need see true and false. But I see true and true. How it fixed?

String str1="asdfgsadgs";
String str2 = "asd fgsx cgvbn adgs";
bool res = Regex.Match(str1, @"[a-zA-Z]|.").Success;
bool res2 = Regex.Match(str2, @"[a-zA-Z]|.").Success;
Console.WriteLine(res);
Console.WriteLine(res2);

Upvotes: 1

Views: 192

Answers (2)

Rawling
Rawling

Reputation: 50104

Your first issue is that . in a regular expression, in general, means "any character". Thus [a-zA-Z]|. means "a letter, or any character", and will match a space.

You either need to

  • escape the ., by putting a \ in front of it, giving @"[a-zA-Z]|\.", or
  • move it inside the character class, where it no longer needs to be escaped, giving @"[a-zA-Z.]"

Your second issue, as Benoit points out, is that your regular expression is asking "does any character matching this class exist anywhere in the input", where you really want to ask "does every character in the input match the class". I won't duplicate his answer here.

Upvotes: 1

Benoit Blanchon
Benoit Blanchon

Reputation: 14521

I think you want this regex

 ^[a-zA-Z]+$

Upvotes: 1

Related Questions