C# 如何保留 Regex.Split 的分隔符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15667927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:31:51  来源:igfitidea点击:

How to keep the delimiters of Regex.Split?

c#regexsplit

提问by

I'd like to split a string using the Splitfunction in the Regexclass. The problem is that it removesthe delimiters and I'd like to keep them. Preferably as separate elements in the splitee.

我想使用类中的Split函数拆分字符串Regex。问题是它删除了分隔符,我想保留它们。最好作为被拆分对象中的单独元素。

According to other discussionsthat I've found, there are only inconvenient ways to achieve that.

根据我发现的其他讨论,只有不方便的方法才能实现这一目标。

Any suggestions?

有什么建议?

采纳答案by Markus Jarderot

Just put the pattern into a capture-group, and the matches will also be included in the result.

只需将模式放入捕获组中,匹配项也将包含在结果中。

string[] result = Regex.Split("123.456.789", @"(\.)");

Result:

结果:

{ "123", ".", "456", ".", "789" }

This also works for many other languages:

这也适用于许多其他语言:

  • JavaScript: "123.456.789".split(/(\.)/g)
  • Python: re.split(r"(\.)", "123.456.789")
  • Perl: split(/(\.)/g, "123.456.789")
  • JavaScript:"123.456.789".split(/(\.)/g)
  • 蟒蛇re.split(r"(\.)", "123.456.789")
  • 珀尔split(/(\.)/g, "123.456.789")

(Not Java though)

(虽然不是Java)

回答by Michael Ross

Add them back:

将它们添加回来:

    string[] Parts = "A,B,C,D,E".Split(',');
    string[] Parts2 = new string[Parts.Length * 2 - 1];
    for (int i = 0; i < Parts.Length; i++)
    {
        Parts2[i * 2] = Parts[i];
        if (i < Parts.Length - 1)
            Parts2[i * 2 + 1] = ",";
    }

回答by Guffa

Use Matchesto find the separators in the string, then get the values and the separators.

使用Matches查找字符串中的分隔符,然后得到的值和分隔符。

Example:

例子:

string input = "asdf,asdf;asdf.asdf,asdf,asdf";

var values = new List<string>();
int pos = 0;
foreach (Match m in Regex.Matches(input, "[,.;]")) {
  values.Add(input.Substring(pos, m.Index - pos));
  values.Add(m.Value);
  pos = m.Index + m.Length;
}
values.Add(input.Substring(pos));

回答by I4V

Say that input is "abc1defg2hi3jkl" and regex is to pick out digits.

假设输入是“abc1defg2hi3jkl”,正则表达式是挑选数字。

String input = "abc1defg2hi3jkl";
var parts = Regex.Matches(input, @"\d+|\D+")
            .Cast<Match>()
            .Select(m => m.Value)
            .ToList();

Parts would be: abc1defg2hi3jkl

部分将是: abc1defg2hi3jkl