Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex only checks first character in string C# [duplicate]

Tags:

c#

regex

Why does the following method only check the first character in the supplied string?

public static bool IsUnicodeSms(string message)
{
   var strMap = new Regex(@"^[@£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,-./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~]|€]+$");
   return !strMap.IsMatch(message);
}

So for example the following string returns false: "abcლ" but "ლabc" returns true.

like image 444
astralmaster Avatar asked Mar 21 '26 08:03

astralmaster


1 Answers

You have to escape ] with \] and also put the - at the end:

Change this:

var strMap = new Regex(@"^[@£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,-./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~]|€]+$");

To this:

var strMap = new Regex(@"^[@£$¥èéùìòÇØøÅå_ÆæßÉ!""#%&'()*+,./0123456789:;<=>? ¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\[~\]|€-]+$");

Btw, you can improve your regex and use:

var strMap = new Regex(@"^[@£$¥èéùìòÇØøÅå_ÆæßÉ!"#%&'()*+,./\w:;<=>? ¡ÄÖÑܧ¿äöñüà^{}\[~\]|€-]+$");

And not sure if using the ignore case flag might help you to shorten it a little more like this:

var strMap = new Regex(@"(?i)^[@£$¥èéùìòÇøå_Ææß!"#%&'()*+,./\w:;<=>? ¡§¿äöñüà^{}\[~\]|€-]+$");
like image 98
Federico Piazza Avatar answered Mar 23 '26 00:03

Federico Piazza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!