1

Let us say we have following regex code lines in Javascript:

.replace(/[\*\+\-=~><\"\?^\${}\(\)\:\!\/[\]\\\s]/g, '\\$&') // replace single character special characters

.replace(/\|\|/g, '\\||') // replace ||

.replace(/\&\&/g, '\\&&') // replace &&

.replace(/AND/g, '\\A\\N\\D') // replace AND

.replace(/OR/g, '\\O\\R') // replace OR

.replace(/NOT/g, '\\N\\O\\T'); // replace NOT

I am trying to translate these regex code lines to following C# Regex Expressions:

 public static String ReturnSanitizedString(string query)
    {
        String pattern1 = @"[\*\+\-=~><\""\?^\${ }\(\)\:\!\/[\]\\\s]"; // Replace the single character special characters. 
        String pattern2 = @"\|\|";
        String pattern3 = @"\&\&";
        String pattern4 = @"AND";
        String pattern5 = @"OR";
        String pattern6 = @"NOT";

        String replacement1 = "\\$&";
        String replacement2 = "\\||";
        String replacement3 = "\\&&";
        String replacement4 = "\\A\\N\\D";
        String replacement5 = "\\O\\R";
        String replacement6 = "\\N\\O\\T";

        Regex rgx = new Regex(pattern1);
        string result1 = rgx.Replace(query, replacement1);

        Regex rgx2 = new Regex(pattern2);
        string result2 = rgx2.Replace(result1, replacement2);

        Regex rgx3 = new Regex(pattern3);
        string result3 = rgx3.Replace(result2, replacement3);

        Regex rgx4 = new Regex(pattern4);
        string result4 = rgx4.Replace(result3, replacement4);

        Regex rgx5 = new Regex(pattern5);
        string result5 = rgx5.Replace(result4, replacement5);

        Regex rgx6 = new Regex(pattern6);
        string finalResult = rgx6.Replace(result5, replacement6);

        return finalResult;
    }

The following sentence(this is the query):

"AND there! are? (lots of) char*cters 2 ^escape!"

Should be converted to this sentence after executing above code:

\A\N\D\ there\!\ are\?\ \(lots\ of\)\ char\*cters\ 2\ \^escape\!

I am not able to get this working, what am I doing incorrect in method above.

3
  • 2
    You're not changing the rgx object for each replace..... a.k.a you're using that same object for each replace... Commented Mar 20, 2017 at 11:33
  • Yes, thats right. I have changed it, but still I am not getting expected output. I am not sure where I am making a mistake. Commented Mar 20, 2017 at 11:39
  • 1
    stackoverflow.com/questions/3982608/… Commented Mar 20, 2017 at 11:41

1 Answer 1

1

In pattern3, you have regex \&\&| which matches basically everything. Just remove the last pipe like this and get what you want:

String pattern3 = @"\&\&";
Sign up to request clarification or add additional context in comments.

Comments

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.