Search code examples
c#stringexpressionncalc

How to escape single quote within string variable in NCalc.Expression - Backslash didn't work


I am using NCalc.Expression to evaluate a condition which involves comparison with string values that contain single quote within them. In NCalc, string is represented using single quote instead of double quotes.

Ex:

[variable1]=='Sample's Data'

In order to escape the single quote, I tried appending a backlash like this -

[variable1]=='Sample\'s Data'

But when this is assigned to a string variable, it removes the backslash as -

[variable1]=='Sample's Data'

and after assigning this to the Expression constructor, it throws an error when evaluated that text after the second single quote "s Data" is not recognized.

When I try appending two backslashes as below -

[variable1]=='Sample\\'s Data',

this is assigned to a string variable as

"[variable1]=='Sample\'s Data'"

but evaluating it doesn't throw the exception but fails the comparison since the data is

"[variable1]=='Sample's Data'"

without the backslash.

How do I solve this?


Solution

  • A possible way is to use the Unicode code point for ' which is U+0027

    var e = new Expression(@"'Sample\u0027s Data'");
    var evaluated = e.Evaluate();
    

    Source

    Or simply:

    var e = new Expression(@"'Sample\'s Data'");
    var evaluated = e.Evaluate();
    

    Without a verbatim string:

    var e = new Expression("'Sample\\'s Data'");
    var evaluated = e.Evaluate();
    

    This gives true:

    var e = new Expression("variable=='Sample\\'s Data'");
    e.Parameters["variable"] = "Sample's Data";
    var evaluated = e.Evaluate();