Regular expression for special characters in C #

I have country names that contain some special characters.

  • CONGO, DEM. REP. OF
  • COTE DIVOIRE
  • GUINEA-BISAU
  • KOREA, REPUBLIC (SOUTH)

So, I wrote a regular expression to confirm the name of the country, which should not contain any numeric and special characters, except,. ' - ( )

I wrote below regex

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

but it just does nothing. Can someone please let me know what I'm doing wrong.

+5
source share
3 answers

If you plan to allow curly apostrophes as well, just add it to the character class:

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

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

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

WITH#:

 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

+2
source

Add ' to character list

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

Try this template:

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

Demo

+1
source

All Articles