vb.net 在简单的词法分析器中识别关键字

vb.net identify keyword in simple lexical analyser

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

我当前的代码:

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

考虑对您的代码进行以下更新(作为控制台项目):

  • 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