Working
Working

Reputation: 3

Regex correct implementation

This should be simple, but bear with me here please. What is it that I'm overlooking? All I'm trying to do is take in a value that is part of a SQL query and I want to check to make sure it has integers as its value. If it is, then I allow it to be passed to SQL Server. I'm getting a notification that my Regex method has invalid arguments. Thanks in advance for shedding some light on where I'm erring.

 string valid2Regex = @"\d{4}"; // regex to check for 4 integers
 Regex rgx = new Regex(valid2Regex);
 string idCheck = id;

 if (rgx.Matches(idCheck, rgx))
        {
            parameters.Add(DataAccess.CreateParameter("@YEAR", SqlDbType.NVarChar, HttpContext.Request.QueryString.Get("Year")));
        } 

Upvotes: 0

Views: 152

Answers (2)

mdn
mdn

Reputation: 252

talking about syntax, you can use Regex in different ways:

string match = rgx.Match(idCheck);

in the this case you look for expression and expect a single result, es:

expr:"\d{4}"   text:"asdfas1234asdfasd"  -> "1234"
expr:"\d{4}"   text:"1234"               -> "1234"
expr:"^\d{4}$" text:"asdfas1234asdfasd"  -> null
expr:"^\d{4}$" text:"1234"               -> "1234"

if you want only to check if the string matches you can use:

bool found = rgx.IsMatch(idCheck);

that works as:

expr:"\d{4}"   text:"asdfas1234asdfasd"  -> true
expr:"\d{4}"   text:"1234"               -> true
expr:"^\d{4}$" text:"asdfas1234asdfasd"  -> false
expr:"^\d{4}$" text:"1234"               -> true

the method (Matches) in your code is used find multiple instances and returns a MatchCollection:

MatchCollection result = rgx.Matches(idCheck, 0);

probably the error in your is about the second parameter, according to MSDN is an integer and represents the start position in the string.

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31576

^\d{4}$

This constrains it to just 4 digits. Otherwise any 4 digits together within a string would work with yours.

Also, there is no instance overload which takes those 2 parameters, instead use IsMatch:

if (rgx.IsMatch(idCheck))
{
    ...

Upvotes: 2

Related Questions