c# 正则表达式问题 "Find SQL Template Parameter in string"
c# Regex Question "Find SQL Template Parameter in string"
我正在尝试解析 SQL 字符串并查找 SQL 模板参数格式的字符串。即 <名称、类型、值>。我正在将该数据解析为 Dictionary。我不是 Regex 方面的专家,但这似乎是找到特定格式的最佳方法,我似乎无法理解我正在寻找的 Regex 命令。
<.+?>
会得到我正在寻找的模板参数,而且还会捕获
的常见 Where 语句的一部分
WHERE (Column < value) or (column > value2)
查找“”的所有实例的 Regex 命令是什么,我尝试的所有内容都找不到任何东西,所以我确信我今天出于某种原因没有完全掌握 Regex。
这应该适合您,这是一个 javascript 示例,但如果您需要考虑除 a-zA-Z0- 之外的其他字符,您可以将其更改为 C# 9@_ 然后将这些字符添加到括号表达式中:
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]);
}
编辑
这是一个 C# 示例:
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);
}
对于广泛匹配,您可以使用取反字符 class:
匹配除 ,
<
>
以外的非空白字符
<(?:[^\s<>,]+\s*,\s*){2}[^\s<>,]+>
模式匹配:
<
字面匹配
(?:
非捕获组
[^\s<>,]+
匹配除 <
>
和 ,
以外的 1+ 个非空白字符
\s*,\s*
匹配可选空白字符之间的逗号
){2}
关闭非捕获组重复2次
[^\s<>,]+
匹配除 <
>
和 ,
以外的 1+ 个非空白字符
>
字面匹配
看到一个regex demo。
如果只有第一个值可以以 @ 开头,您可以使模式更严格,并以 @ 和 1 个或多个单词字符匹配开头 \w+
并且第二个和第三个值只能使用单词字符:
<@\w+\s*,\s*\w+\s*,\s*\w+>
我正在尝试解析 SQL 字符串并查找 SQL 模板参数格式的字符串。即 <名称、类型、值>。我正在将该数据解析为 Dictionary
<.+?>
会得到我正在寻找的模板参数,而且还会捕获
的常见 Where 语句的一部分WHERE (Column < value) or (column > value2)
查找“
这应该适合您,这是一个 javascript 示例,但如果您需要考虑除 a-zA-Z0- 之外的其他字符,您可以将其更改为 C# 9@_ 然后将这些字符添加到括号表达式中:
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]);
}
编辑
这是一个 C# 示例:
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);
}
对于广泛匹配,您可以使用取反字符 class:
匹配除,
<
>
以外的非空白字符
<(?:[^\s<>,]+\s*,\s*){2}[^\s<>,]+>
模式匹配:
<
字面匹配(?:
非捕获组[^\s<>,]+
匹配除<
>
和,
以外的 1+ 个非空白字符
\s*,\s*
匹配可选空白字符之间的逗号
){2}
关闭非捕获组重复2次[^\s<>,]+
匹配除<
>
和,
以外的 1+ 个非空白字符
>
字面匹配
看到一个regex demo。
如果只有第一个值可以以 @ 开头,您可以使模式更严格,并以 @ 和 1 个或多个单词字符匹配开头 \w+
并且第二个和第三个值只能使用单词字符:
<@\w+\s*,\s*\w+\s*,\s*\w+>