C# regex.split 方法在括号前添加空字符串
我有一些代码将方程式输入标记为字符串数组:
string infix = "( 5 + 2 ) * 3 + 4";
string[] tokens = tokenizer(infix, @"([\+\-\*\(\)\^\\])");
foreach (string s in tokens)
{
Console.WriteLine(s);
}
现在这是标记器函数:
public string[] tokenizer(string input, string splitExp)
{
string noWSpaceInput = Regex.Replace(input, @"\s", "");
Console.WriteLine(noWSpaceInput);
Regex RE = new Regex(splitExp);
return (RE.Split(noWSpaceInput));
}
当我运行此函数时,我将所有字符分开,但在括号字符之前插入了一个空字符串...我该如何删除这?
//此处为空字符串
(
5
+
2
//此处为空字符串
)
*
3
+
4
I have some code that tokenizes a equation input into a string array:
string infix = "( 5 + 2 ) * 3 + 4";
string[] tokens = tokenizer(infix, @"([\+\-\*\(\)\^\\])");
foreach (string s in tokens)
{
Console.WriteLine(s);
}
Now here is the tokenizer function:
public string[] tokenizer(string input, string splitExp)
{
string noWSpaceInput = Regex.Replace(input, @"\s", "");
Console.WriteLine(noWSpaceInput);
Regex RE = new Regex(splitExp);
return (RE.Split(noWSpaceInput));
}
When I run this, I get all characters split, but there is an empty string inserted before the parenthesis chracters...how do I remove this?
//empty string here
(
5
+
2
//empty string here
)
*
3
+
4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会把它们过滤掉:
I would just filter them out:
您所看到的是因为您没有任何分隔符(即在字符串的开头是
(
),然后是两个相邻的分隔符(即)*
在中间)。这是设计使然。正如您可能在 String.Split 中发现的那样,该方法有一个可选的枚举,您可以提供该枚举以让它删除任何空条目,但是,正则表达式没有这样的参数。在您的具体情况下,您可以简单地忽略长度为 0 的任何标记。
What you're seeing is because you have nothing then a separator (i.e. at the beginning of the string is
(
), then two separator characters next to one another (i.e.)*
in the middle). This is by design.As you may have found with
String.Split
, that method has an optional enum which you can give to have it remove any empty entries, however, there is no such parameter with regular expressions. In your specific case you could simply ignore any token with a length of 0.好吧,一种选择是事后过滤掉它们:
Well, one option would be to filter them out afterwards:
试试这个(如果你不想过滤结果):
Perl demo:
不过在这种情况下,我认为最好使用匹配而不是拆分。
Try this (if you don't want to filter the result):
Perl demo:
Altho it would be better to use a match instead of split in this case imo.
我认为你可以通过分割使用 [StringSplitOptions.RemoveEmptyEntries]
I think you can use the [StringSplitOptions.RemoveEmptyEntries] by the split