Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if part of string matches regex

Tags:

c#

regex

I am trying to validate strings according to various regular expressions; however, if whitespace characters get added to the end of the string, they do not get flagged anymore.

if (Regex.IsMatch(literal.Value.ToString().ToLower(), @"^\+?[0-9\-\(\)\.\/]{8,20}$")
{
    //Logic
}

In the following piece of code; the X-value gets flagged but the Z-value does not.

string x = "0337350670"; // Gets flagged
string z = "0337350670     "; // Does not get flagged

Should I change my regular expression or is there a way to validate against a part of the string?

like image 372
Matthijs Avatar asked Sep 12 '25 09:09

Matthijs


1 Answers

You can just Trim your string to remove trailing whitespaces from both sides.

Also, many special regex characters aren't special anymore inside a character class (- still is, but is escaped if you put it like so: [...-]).

Regex.IsMatch(literal.Value.ToString().ToLower().Trim(),
              @"^\+?[0-9()./-]{8,20}$"

Removing ^$ would work too, but be aware this would allow strings composed of more than 20 digits in a row: you don't check the maximum length anymore (anything containing [0-9()./-]{8} would match).

like image 70
Robin Avatar answered Sep 14 '25 00:09

Robin