问题描述
我正在使用NCalc.Expression评估条件,该条件涉及与其中包含单引号的字符串值进行比较.在NCalc中,字符串使用单引号而不是双引号表示.
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.
例如:
[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'
,并将其分配给Expression构造函数后,当评估出第二个单引号"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'"
没有反斜杠.
我该如何解决?
推荐答案
一种可能的方法是对'
使用Unicode代码点,即 U + 0027
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();
或者简单地:
var e = new Expression(@"'Sample\'s Data'");
var evaluated = e.Evaluate();
没有逐字字符串:
var e = new Expression("'Sample\\'s Data'");
var evaluated = e.Evaluate();
这给出了true
:
var e = new Expression("variable=='Sample\\'s Data'");
e.Parameters["variable"] = "Sample's Data";
var evaluated = e.Evaluate();
这篇关于如何在NCalc.Expression中的字符串变量中转义单引号-反斜杠不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!