Matt
Matt

Reputation: 22113

Why does this Regex not match properly?

I basically have this:

Regex rx = new Regex(@"\$(?:(\$)|(\{(?<ex>.*?)\}))");
string s = "${P#(n*8+1)!=0$$P}${P#(n*8+1)!=0$N/A$[n*8+1]}";

Match m = rx.Match(s, 0);

The first match is "${P#(n*8+1)!=0$N/A$[n*8+1]}" when it should be "${P#(n*8+1)!=0$$P}". If I put an extra space before the first '$', it works fine.

Upvotes: 2

Views: 86

Answers (1)

e_ne
e_ne

Reputation: 8459

You are swapping the arguments. Regex.IsMatch signature is:

public static bool IsMatch(string input, string pattern)

EDIT: the following code prints True twice for me.

var p = @"\$(?:(\$)|(\{(?<ex>.*?)\}))";
var regex = new Regex(p);
Console.WriteLine(regex.IsMatch(" ${foo}"));
Console.WriteLine(regex.IsMatch("${foo}"));

EDIT2: deleted the previous edit, the match works for me.

Upvotes: 4

Related Questions