MrASifuMason MrASifuMason - 2 months ago 7
C# Question

C# regex end of string

I tried to make something work that I found on msdn and was looking for some help. Im trying to find where there is an (asterisk, wildcard, star) which will be at the end of the string, and return that match. Where did I go wrong with my pattern?

static void Main(string[] args)
{
string pattern;
pattern = ("*$");
Regex rgx = new Regex(pattern);

string[] tests =
{
"42", ".45", "3452013232", "2015550777*"
};

foreach (string test in tests)
{
if(rgx.IsMatch(test))
Console.WriteLine(test);
else
Console.WriteLine("No Matches!");
}
Console.ReadLine();
}


Thanks!

Answer

Asterisk has a special meaning in a regular expression. If you want to match an actual asterisk you have to escape it. Try:

pattern = @"\*$"
Comments