1

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"

here "key" is a reserved keyword.which has to be modified as "Select [key] from table1" (which will work in 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?

1
  • Key|IN|ON|VIEW] wrong pattern... Commented Aug 27, 2014 at 9:18

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

if the query contains "[Key]"..how to ignore that from matching..because if the query already has [Key], after replacement it becomes [[Key]].
That's indeed another question, ask new question please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.