I am not able to figure out the simple compile error I am getting on Regex.Match
method.
The error says
Cannot access non-static method 'IsMatch' in static context
The error text is confusing in itself because the method I am calling is the static method of the Regex
class while the error says that I cannot access non-static
method in statc context.
My context is also not static
because the method in which I have calling Regex.IsMatch
function is a non-static method, even the class is also non static.
The error is confusing!
It works when I replace the call with the Regex class' instance call like this
new Regex(@"/^(?:2[89]|[3-9]\d)\d{6,}$/").IsMatch(@"/^(?:2[89]|[3-9]\d)\d{6,}$/")
But I am totally confused of why can't I call the static method of the class!
CodePudding user response:
There is no static
method IsMatch
accepting only one parameter.
IsMatch(string input, string pattern)
is static
, but IsMatch(string input)
is not and needs to be called on an instance that already has been given a pattern (because, thinking about it, what pattern would be used if this method was static
and we only provide an input string to it?)
Here is where you can find all available overloads.
CodePudding user response:
You need to provide an input string to the Regex.IsMatch
method.
However, you also need to amend the regex and remove the leading and trailing slashes that you must be using as regex delimiter chars. Those slashes are treated as part of a pattern and will prevent your regex from matching any string. Remember that regular expressions are defined with string literals ("..."
) in C#, not with regex literals (/.../
).
So you need to use
Regex.IsMatch(item.HSCode, @"^(?:2[89]|[3-9]\d)\d{6,}$")
Also, consider using [0-9]
instead of \d
if you only expect ASCII digits in the input, see \d less efficient than [0-9].