1

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?

DaniDev
  • 2,471
  • 2
  • 22
  • 29
  • Did you try with 4 `\ `? – Thomas Ayoub Mar 07 '16 at 21:48
  • I answered with the possible ways of escaping a quote in an expression. If these are not what you're looking for, then please give a minimal, reproducable example that we can paste into VS and use to help fix the issue. – Szabolcs Dézsi Mar 07 '16 at 21:58

2 Answers2

1

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();
Szabolcs Dézsi
  • 8,743
  • 21
  • 29
  • Maybe I'm missing something, but other than the \u0027 suggestion, how are the others different than what he already tried? – dmeglio Mar 07 '16 at 21:55
  • Just showing the ways of escaping the quote in an expression. Maybe I don't understand his question then. I thought that's what he has a problem with. If not then he should give a code example I can copy into VS and fix it. – Szabolcs Dézsi Mar 07 '16 at 21:57
  • Thank you for the response. The Unicode approach worked fine. I had tried the other options but they didn't work due to the exception I mentioned initially. Appreciate your quick response. – Kiran Lakshmikantha Mar 08 '16 at 16:04
0

According to the wiki https://ncalc.codeplex.com/wikipage?title=values&referringTitle=Home#strings

You can escape special characters using \\, \', \n, \r, \t.

drzaus
  • 24,171
  • 16
  • 142
  • 201
  • That link is soooo dead; this one seems slightly newer https://github.com/ncalc/ncalc/wiki/Values – drzaus Aug 28 '18 at 14:04