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

白昼怎懂夜的黑 提交于 2019-12-13 01:59:17

问题


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?


回答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();



回答2:


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

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



来源:https://stackoverflow.com/questions/35854525/how-to-escape-single-quote-within-string-variable-in-ncalc-expression-backslas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!