Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for special characters in c#

Tags:

c#

regex

I have below country names which contains some special characters.

  1. CONGO, DEM. REP. OF THE
  2. COTE D’IVOIRE
  3. GUINEA–BISSAU
  4. KOREA, REPUBLIC OF (SOUTH)

So, I wrote a regular expression to validate that a country name that must not contain any numeric and special characters other than , . ' - ( )

I wrote below regex

string country = "COTE D’IVOIRE"
bool isValid = Regex.IsMatch(country.Trim(), @"^[a-zA-Z\-'()/.,\s]+$");

but it just not doing the thing. Can someone please let me know what I'm doing wrong.

like image 940
Rahul Chakrabarty Avatar asked Aug 06 '15 12:08

Rahul Chakrabarty


2 Answers

If you plan to also allow curly apostrophe, just add it to the character class:

@"^[a-zA-Z’\-'()/.,\s]+$"
          ^

Note that you do not have to escape - if it is at the end of the character class and you can use (?i) case-insensitive modifier to shorten the a-zA-Z part:

@"(?i)^[a-z’'()/.,\s-]+$"

C#:

string country = "COTE D’IVOIRE";
bool isValid = Regex.IsMatch(country.Trim(), @"(?i)^[a-z’'()/.,\s-]+$");
// or use RegexOptions.IgnoreCase option
//bool isValid = Regex.IsMatch(country.Trim(), @"^[a-z’'()/.,\s-]+$", RegexOptions.IgnoreCase);

enter image description here

like image 190
Wiktor Stribiżew Avatar answered Nov 05 '22 16:11

Wiktor Stribiżew


Add the to the list of symbols

string country = "COTE D’IVOIRE"
bool isValid = Regex.IsMatch(country.Trim(), @"^[a-zA-Z\-'’()/.,\s]+$");
like image 32
thomas Avatar answered Nov 05 '22 15:11

thomas