2016-12-08 89 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語句可用於輸入數字.. –