2016-12-08 34 views
1

我有一个vb.net正则表达式,我正用它来识别简单的z + x总和中的运算符。如何使用词法分析来识别给定表达式中的关键字?vb.net在简单的词法分析器中识别关键字

我当前的代码:

Dim input As String = txtInput.Text 
Dim symbol As String = "([-+*/])" 
Dim substrings() As String = Regex.Split(input, symbol) 

For Each match As String In substrings 
    lstOutput.Items.Add(match) '<-- Do I need to add a string here to identify the regular expression? 
Next 

input: z + x 

这就是我想要的输出

z - keyword 
+ - operator 
x - keyword 

回答

2

考虑以下更新到您的代码发生(如一个控制台项目):

  • operators包含一个字符串,您可以在您的Regex模式,同时参考后来
  • 在循环,检查是否operators包含match这意味着与之匹配的是运营商
  • 别的是一个关键字

因此,这里的代码:

Dim input As String = "z+x" 
Dim operators As String = "-+*/" 
Dim pattern As String = "([" & operators & "])" 
Dim substrings() As String = Regex.Split(input, pattern) 
For Each match As String In substrings 
    If operators.Contains(match) Then 
     Console.WriteLine(match & " - operator") 
    Else 
     Console.WriteLine(match & " - keyword") 
    End if 
Next 
+0

感谢罗宾我也没有else if语句可用于输入数字.. –