保留Regex.Split中所有生成的子字符串中的分隔符?

huangapple go评论76阅读模式
英文:

C# - How to keep the delimiters of Regex.Split in all resulting substrings?

问题

我想使用 Regex.Split 来根据分隔符进行拆分,并且让该分隔符拆分到所有子字符串中。

例如:
我有一个字符串 ""holidays//2024"",分隔符是 "''",我希望得到以下结果:""holidays/"",""/2024""

这个 帖子展示了如何拆分并保留分隔符作为结果的独立元素。我还能够分别使用 Lookbehind "(?<=[])" 和 Lookahead "(?=[])",每个都实现了所需结果的一半。我正在努力看如何同时使用两者(或其他解决方案)以在单个表达式中实现所需的结果。

有任何建议吗?

英文:

I'd like to use Regex.Split to split on a delimiter, and also have that delimiter split onto all substrings.

For Example:
I have a string &quot;holidays/*/2024&quot;, and separator &#39;*&#39; and I want to have following: &quot;holidays/*&quot;,&quot;*/2024&quot;

This thread shows how to split and keep the separators as their own elements of the result. I have also been able to use Lookbehind (?&lt;=[*]) and Lookahead (?=[*]) separately, each achieving half of the desired result. I am struggling to see how to use both (or alternative solutions) to accomplish the desired result in a single expression.

Any suggestions?

答案1

得分: 1

使用正则表达式分割字符串。

        using System;
        using System.Text.RegularExpressions;
        
        public class Program
        {
            public static void Main()
            {
                string input = &quot;holidays/*/2024&quot;;
                string pattern = @&quot;(?&lt;=\*)|\*(?=/)&quot;;
        
                string[] substrings = Regex.Split(input, pattern);
                foreach (string substring in substrings)
                {
                    Console.WriteLine(substring);
                }
            }
        }

        输出
    
        holidays/
        /2024

希望这有所帮助!
英文:

To split a string using Regex.

    using System;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            string input = &quot;holidays/*/2024&quot;;
            string pattern = @&quot;(?&lt;=\*)|\*(?=/)&quot;;
    
            string[] substrings = Regex.Split(input, pattern);
            foreach (string substring in substrings)
            {
                Console.WriteLine(substring);
            }
        }
    }

    Output

    holidays/
    /2024

I hope this helps!

答案2

得分: 0

我不了解C#,但一个简单的循环应该足够:

string[] splitted = text.Split(delimiter);

for (var i = 0; i &lt; splitted.Length; i++) {
	var fragment = splitted[i];

	if (i &gt; 0) {
		fragment = delimiter + fragment;
	}

	if (i &lt; splitted.Length - 1) {
		fragment += delimiter;
	}

	Console.WriteLine(fragment);
}

你可以在 dotnetfiddle.net 上尝试它。

英文:

I don't know C#, but a simple loop should be enough:

string[] splitted = text.Split(delimiter);

for (var i = 0; i &lt; splitted.Length; i++) {
	var fragment = splitted[i];

	if (i &gt; 0) {
		fragment = delimiter + fragment;
	}

	if (i &lt; splitted.Length - 1) {
		fragment += delimiter;
	}

	Console.WriteLine(fragment);
}

Try it on dotnetfiddle.net.

答案3

得分: 0

以下是翻译好的部分:

另一个解决方案是使用这个看起来很可怕的正则表达式:

Regex re = new Regex(
  @"
    (?:^|\*)        # 匹配并捕获字符串的开头或 '*',
    (?=             # 然后
      ([^*]+)       # 一个包含 1 个或多个非 '*' 字符的组,接着是
      (\*|$)        # 另一个包含 '*' 或字符串结尾的组。
    )
  ",
  RegexOptions.IgnorePatternWhitespace
);

...然后使用 .Join() 在每个匹配中的组中获取最终结果:

MatchCollection matches = re.Matches(text);

foreach (Match match in matches) {
  Console.WriteLine(
    String.Join("", (
      from Group matchGroup in match.Groups
      where matchGroup.ToString() != ""
      select matchGroup.ToString()
    ))
  );
}

dotnetfiddle.net 上尝试

英文:

Another solution is to use this horrible-looking regex:

Regex re = new Regex(
  @&quot;
    (?:^|\*)        # Match and capture either the beginning of string or &#39;*&#39;,
    (?=             # then
      ([^*]+)       # a group 1+ non-&#39;*&#39; characters, followed by
      (\*|$)        # another group of &#39;*&#39; or the end of string.
    )
  &quot;,
  RegexOptions.IgnorePatternWhitespace
);

...then .Join() the groups in each match to get the final result:

MatchCollection matches = re.Matches(text);

foreach (Match match in matches) {
  Console.WriteLine(
    String.Join(&quot;&quot;, (
      from Group matchGroup in match.Groups
      where matchGroup.ToString() != &quot;&quot;
      select matchGroup.ToString()
    ))
  );
}

Try it on dotnetfiddle.net.

huangapple
  • 本文由 发表于 2023年5月26日 01:10:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定