Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex: An object reference is required for the non-static field, method, or property 'Regex.Match(string)'

Tags:

c#

regex

i'm encountering an issue with storing values with RegEx when doing a C# quadratic equation solver. Basically, I want the user to input the equation himself, instead of the program asking for a, b, and c.

Here is what i have:

string regEx = @"(-?\d +)x\^ 2([+-]\d +)x([+-]\d +)";

Match match = Regex.Match(regEx);

The program is done, except for inputting the values. I get this error:

An object reference is required for the non-static field, method, or property 'Regex.Match(string)'

Any ideas as to what I have to do to store the values? I would like to preferably store them in a double array.

like image 205
Noel S.G Avatar asked Oct 22 '25 00:10

Noel S.G


1 Answers

You need both a regex and a string to test, like this:

var regEx = new Regex(@"(-?\d +)x\^ 2([+-]\d +)x([+-]\d +)");

var match = regEx.Match("string to test");

or, if you don't plan to use it more than once you could use the static method like this:

var match = Regex.Match("string to test", @"(-?\d +)x\^ 2([+-]\d +)x([+-]\d +)");

If you want a collection of matches, rather than just the first one, you can get them like this:

var matchCollection = regEx.Matches("string to test");
like image 189
Robin Bennett Avatar answered Oct 23 '25 15:10

Robin Bennett