在使用数学运算符拆分时删除可选的空格,同时将它们保留在结果中

Remove optional whitespace when splitting with math operators while keeping them in the result

如何去除输入字符串中的空白字符?我正在使用以下代码

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


    Dim substrings() As String = Regex.Split(input, symbol)
    Dim cleaned As String = Regex.Replace(input, "\s", " ")
    For Each match As String In substrings
        lstOutput.Items.Add(match)
    Next

输入:z + x

输出:z+ x

我想去掉最后一项中的空格。

您可以在拆分时删除多余的空格

\s*([-+*/])\s*

参见regex demo。此外,最好在将输入传递给 .Trim().

之前 trim 输入

图案详情:

  • \s* - 匹配 0+ 个空格(这些将从结果中丢弃,因为它们未被 捕获
  • ([-+*/]) - 第 1 组(捕获的文本将输出到结果数组)捕获 1 个字符:-+*/
  • \s* - 匹配 0+ 个空格(这些将从结果中丢弃,因为它们未被 捕获