我有这样的线。
string str = "ZeroIfNegative((NonApodCapacity()*0.65*0.9), 1) - ZeroIfNegative(P.BDFWU.dmd_dpt_fc + P.BDFW.dmd_dpt_fc - NonApodCapacity(1,2)*0.35)";我想对它进行相应的拆分,以获得与其参数一起使用的方法,例如
ar[0] = ZeroIfNegative((NonApodCapacity()*0.65*0.9), 1)
ar[1] = ZeroIfNegative(P.BDFWU.dmd_dpt_fc + P.BDFW.dmd_dpt_fc - NonApodCapacity(1,2)*0.35)内部方法也使用NonApodCapacity(1,2)作为另一个字符串。
基本上,我想用它的参数来验证这个方法名,这个参数也可以是一个方法。
发布于 2018-01-19 15:19:26
这可能会变得相当复杂,这取决于验证的实际“深度”。我举了一些例子来说明什么是有效的,什么是无效的。你需要确保方法名,参数类型,计数,正确的嵌套等等吗?从一个简单的例子开始。像这样:
假设这是有效的:NonApodCapacity(1,2)*0.35+P.BDFW.ab
但是NonApodCapacity(5,6,7,8)*0.35+P.BDFW.ab呢?
或NonApodCapacity(1,2)*3,5+P.BDFW.ab
或UnknownFunctionName(1,2)*0.35+P.BDFW.ab
或NonApodCapacity(1,2))*0.35+P.BDFW.ab
或NonApodCapacity(1,2))*0.35+P.BDFWXYZ.abcde
或更多可能的验证...
(发现到处都是不同类型的错误?)
如果我的所有示例都应该被拒绝,那么您在这里得到的是一个表达式树,它需要使用相当复杂的算法进行解析。
MSDN的 Article是一个很好的开始。(这里没有代码片段,因为我不打算提供功能代码位,只是提供一些资源供您进一步阅读)
如果您只是将字符串拆分成片段并验证每个组件,这是非常简单的,但是您的验证永远不会涵盖上述所有情况。
例如,您可以按分隔符列表(例如,、(space)、*、+...)拆分完整的公式。对于你找到的每个组件,检查它是否是一个数字。如果不是,它可能是一个变量/字段名,或者是一个方法名,您可以将其与您的已知方法名列表进行比较。
发布于 2018-01-19 16:17:16
基本上,计算括号的开头和结尾就可以解决这个问题。
var str = "ZeroIfNegative((NonApodCapacity()*0.65*0.9), 1) - ZeroIfNegative(P.BDFWU.dmd_dpt_fc + P.BDFW.dmd_dpt_fc - NonApodCapacity(1,2)*0.35)";
int op_count = 0; // close paren counter
int p_count = 0; // open paren counter
List<string> methods = new List<string>(); // storage of functions
string currentFunc = ""; // the current function
for (var i = 0; i < str.length; i++) {
currentFunc += str[i].toString();
if (string.isNullOrEmpty(str[i].toString())) {
if (op_count == cp_count && (op_count > 0 && cp_count > 0)) {
// add the method to the collection
methods.Add(currentFunc);
// reset
op_count = 0;
cp_count = 0;
currentFunc = "";
}
}
// if its the last character, add it as new method
if (i == str.length - 1) {
methods.Add(currentFunc);
}
if (str[i] == '(') {
op_count++;
}
if (str[i] == ')') {
cp_count++;
}
}
// print the result
foreach (var m in methods) {
Console.Writeline(m);
}
the result will be
ZeroIfNegative((NonApodCapacity()*0.65*0.9), 1)
- ZeroIfNegative(P.BDFWU.dmd_dpt_fc + P.BDFW.dmd_dpt_fc - NonApodCapacity(1,2)*0.35)发布于 2018-01-19 15:01:21
您可以使用C#拆分函数拆分字符串,例如
string str=“巴基斯坦是我的祖国”;
//在拆分函数中,您可以根据//您的要求传递空格或任何其他符号
string[] firstValue=str.Split(',');
https://stackoverflow.com/questions/48335483
复制相似问题