Home > Back-end >  c# Regex Question "Find SQL Template Parameter in string"
c# Regex Question "Find SQL Template Parameter in string"

Time:05-12

I am trying to parse a SQL String and look for SQL Template Parameter formatted strings. i.e. < Name, Type, Value>. I am parsing that data out to a Dictionary<String, Object>. I am not an expert in Regex, but this appears to be the best way to find the specific format, I just cannot seem to wrap my head around the Regex command I am looking for.

<. ?>

Will get me the Template Parameters I am looking for, but also catches part of a common Where statement of

WHERE (Column < value) or (column > value2)

What would be the Regex command to find all instances of "<string,string,stringornumber>" everything I tried fails to find anything, so I am sure I am just not fully grasping Regex for some reason today.

CodePudding user response:

This should work for you, this is a javascript example but you can change it to C#, if you need to account for other characters besides a-zA-Z0-9@_ then just add those characters into the bracket expressions:

const mysql = 'select <@test, int,  10>, <@test2, bigint, 1200000000000> from mytable where (col1 < @test) or (col1 > @test2)';
const matches = mysql.match(/<[a-zA-Z0-9@_] ?,\s*?[a-zA-Z0-9@_] ?,\s*?[a-zA-Z0-9@_] >/g);
for(let a = 0; a < matches.length; a  ){
   console.log(matches[a]);
}

EDIT

Here's a C# Example:

Regex reg = new Regex("<[a-zA-Z0-9@_] ?,\\s*?[a-zA-Z0-9@_] ?,\\s*?[a-zA-Z0-9@_] >", RegexOptions.Multiline);        
string test = "select <@test, int,  10>, <@test2, bigint, 1200000000000> from mytable where (col1 < @test) or (col1 > @test2)";
MatchCollection matches = reg.Matches(test);
foreach(Match m in matches)
{
    Console.WriteLine(m.Value);
}
  • Related