我想生成字符串的条件代码,它将检查字符串。一个例子是以下字符串 sampleString =" C123 A091 A111 A122 B120 B309 C000" 我所拥有的条件字符串的例子如下
示例1: 我会生成 A123 + B123
if sampleString.contains ("A123") And sampleString.contains ("B123") Then
'doSomething
else
'doSomething
end if
示例2: 的 A111 + A122 +(B120 / -C123)
if sampleString.contains ("A111") And sampleString.contains ("A122") And (sampleString.contains ("B120") Or Not sampleString.contains ("C123")) Then
'doSomething
else
'doSomething
end if
我可以在VB.Net中执行此操作吗?
答案 0 :(得分:0)
使用Regex
通过查找匹配项来解决Contains
问题,并将其替换为1或0.
Dim sample As String = "C123 A091 A111 A122 B120 B309 C000"
Dim input As String = "A111 + A122 + ( B120/- C123)"
Dim nRegex As New Regex("\w+", RegexOptions.IgnoreCase)
Dim nMatches As MatchCollection = nRegex.Matches(input)
For Each nMatch As Match In nMatches
input = input.Replace(nMatch.Value, IIf(sample.Contains(nMatch.Value), "1", "0"))
Next
现在将您所拥有的特殊字符替换为在计算为数学表达式时实际可以为您提供正确结果的特殊字符(因为逻辑最初是数学运算)。
input = input.Replace(" ", "")
input = input.Replace("+", "*")
input = input.Replace("/", "+")
input = input.Replace("-1", "0").Replace("-0", "1")
毕竟,你会得到这个表达式:
1*1*(1+0)
您现在可以使用此Answer中建议的任何数学评估程序。如果得到的结果大于零则意味着它的逻辑True
。否则False