[英]How to handle Regex with multiple patterns?
I have a requirement where I need to read a query from access db and modify the query to replace all the keywords in the query to SQL executable query.. For eg: say there is a query 'Select key from table1" 我有一个需要从访问数据库读取查询并修改查询以将查询中的所有关键字替换为SQL可执行查询的要求。例如:说有一个查询“从table1中选择键”
here "key" is a reserved keyword.which has to be modified as "Select [key] from table1" (which will work in sql). 这里“ key”是一个保留关键字。必须将其修改为“从table1中选择[key]”(将在sql中起作用)。
there is a possibility that the query can have multiple keywords..so I have a regex as below. 查询可能有多个关键字..所以我有一个正则表达式如下。
string pattern = "Key|IN|ON|VIEW]";
Regex rgx = new Regex(pattern);
I have the below code..which checks for the patterns.. 我有下面的代码..其中检查模式..
string pattern = "Key|IN|ON|VIEW]";
Regex rgx = new Regex(pattern);
string strModifiedQuery = string.Empty;
strModifiedQuery = strQueryText;
foreach (Match m in rgx.Matches(pattern))
{
Console.WriteLine(m.Value);
if (m.Value == "Key")
{
strModifiedQuery = rgx.Replace(strModifiedQuery, "[Key]");
}
if (m.Value == "IN")
{
strModifiedQuery = rgx.Replace(strModifiedQuery, "[IN]");
}
if (m.Value == "ON")
{
strModifiedQuery = rgx.Replace(strModifiedQuery, "[IN]");
}
Is there a better way in c# to replace the matched pattern with a proper value? 在c#中是否有更好的方法将匹配的模式替换为适当的值?
var pattern = @"(?i)Key|IN|ON|VIEW";
var subject = "Select key from table1";
var result = Regex.Replace(subject, pattern, @"[$0]");
Produces 产生
Select [key] from table1
(?i)
turns on ignore case and replace pattern [$0]
replaces whatever matched surrounded by brackets. (?i)
打开忽略大小写,替换模式[$0]
替换括号中匹配的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.