C# 将if语句转换为条件语句
我正在尝试转换C# 将if语句转换为条件语句,c#,regex,replace,C#,Regex,Replace,我正在尝试转换IF语句,如下所示 SET RESULT = IF(C>(X-2), (A+B), C) //IF C< X-2 return A+B otherwise return C SET RESULT = C>(X-2)?(A+B):C 我已经编写了一个代码,它扫描整个字符串并查看出现的IF,(和,)语句。当出现多个IF语句时,我的算法不起作用,如下所示 SET RESULT = IF(C>(X-2), IF(P>C,2,3),C) 这是代码
IF
语句,如下所示
SET RESULT = IF(C>(X-2), (A+B), C) //IF C< X-2 return A+B otherwise return C
SET RESULT = C>(X-2)?(A+B):C
我已经编写了一个代码,它扫描整个字符串并查看出现的IF
,(
和,
)语句。当出现多个IF
语句时,我的算法不起作用,如下所示
SET RESULT = IF(C>(X-2), IF(P>C,2,3),C)
这是代码
string data = "SET RESULT=IF(C>(X-2), (A+B), C)";
string output = string.Empty;
int indexofIF = data.IndexOf("IF");
int obCount = 0;
int cbCount = 0;
if (indexofIF > -1)
{
string script = data.Substring(indexOfIF, (data.Length-indexOfIF-1))
for(int index=0; index<script.Length; index++)
{
int obIndex = data.IndexOf('(', index);
if(obIndex>-1)
obCount++;
int cbIndex = data.IndexOf(')', index);
if(cbIndex>-1)
cbCount++;
if(obCount==cbCount)//Found the end of If statement
{
string tempData = data.Substring(0, index);
int count = tempData.Count(f => f == ',');//Get the number of occurences of ','
if (count == 2)//There are only 2 commas
{
int firstIndex = tempData.IndexOf(',');
int lastIndex = tempData.LastIndexOf(',');
string condtion = tempData.Substring(3, (firstIndex - 4));
string trueCond = tempData.Substring(firstIndex + 1, (lastIndex - firstIndex - 1));
string falseCond = tempData.Substring(lastIndex + 1, (index - lastIndex - 1));
output = condtion + "?" + trueCond + ":" + falseCond;
}
else //More than 2 commas
{
}
}
}
}
string data=“SET RESULT=IF(C>(X-2),(A+B),C)”;
字符串输出=string.Empty;
int indexofIF=data.IndexOf(“如果”);
int obCount=0;
int cbCount=0;
如果(indexofIF>-1)
{
字符串脚本=data.Substring(indexOfIF,(data.Length-indexOfIF-1))
对于(int-index=0;index-1)
obCount++;
int cbIndex=data.IndexOf('),index);
如果(cbIndex>-1)
cbCount++;
if(obCount==cbCount)//找到if语句的结尾
{
字符串tempData=data.Substring(0,索引);
int count=tempData.count(f=>f=',');//获取','的出现次数
if(count==2)//只有2个逗号
{
int firstIndex=tempData.IndexOf(',');
int lastIndex=tempData.LastIndexOf(',');
字符串条件=tempData.Substring(3,(firstIndex-4));
字符串trueCond=tempData.Substring(firstIndex+1,(lastIndex-firstIndex-1));
字符串falseCond=tempData.Substring(lastIndex+1,(index-lastIndex-1));
输出=条件+“?”+trueCond+”:“+falseCond;
}
else//超过2个逗号
{
}
}
}
}
我不确定这是否适用于复杂的场景。还有其他更好的方法吗?可能使用
regex
或任何其他字符串替换操作。您的操作是正确的
我想:
- 将每个字符读入一个小缓冲区
- 计算缓冲区以查找单词“IF”
- 设置一个标志,使您知道自己在IF语句中
- 清除缓冲区
- 为括号求值
- 跟踪括号的打开/关闭
- 执行任何附加逻辑(例如逗号解析)
- 继续,直到字符串结束
(IF.*?(?=IF |$)
中断多个IF语句,但它不处理额外的解析,并要求输入数据遵循严格的结构。跟踪括号是很棘手的/不可能的(参见此答案的注释),并且更容易由状态机处理
就我个人而言,我喜欢逐字符分析的控制/灵活性。像这样的工具使用这种方法来解析源代码
您可能会发现,一旦成功提取了字符串的一部分,正则表达式就非常有用(例如,将
a+B>C
等公式分解为各个部分)。任意嵌套的paren匹配不是一种常规语言,因此,除非你约束问题空间,否则你不会找到一个纯粹的正则表达式解决方案。@RaymondChen-同意,我能使正则表达式起作用的唯一方法是将输入数据约束到固定数量的括号中,我认为这不是一个可行的解决方案。FWIW,Perl5的所谓“正则表达式”,以及许多借用它的语言中的正则表达式,实际上可以使用递归插值匹配任意嵌套的分隔符对。并不是说我会建议你去做。无论如何,我认为C#不能。