使用Regex隔离多个匹配项之间的内容

时间:2012-07-11 18:07:47

标签: c# regex

我的字符串如下所示: “1y 250 2y 32%3y otherjibberish”。

我的最终目标是将其分为以下几种: “1y 250” “2y 32%” “3y otherjibberish”

这些分割之间的主要“分隔符”是“\ d + y”模式。使用Regex(C#4.0),我可以使用Matches函数匹配一个数字后跟一个'y',但我不知道如何获得该匹配后的所有内容,但在下一个匹配之前。

有办法吗?

希望这是有道理的......非常感谢 - kcross

2 个答案:

答案 0 :(得分:2)

您可以使用“MatchCollection”根据事件拆分字符串。 以下示例几乎可以满足您的需求。不删除每个字符串右侧的空白字符。

代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Q11438740ConApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceStr = "1y 250 2y 32% 3y otherjibberish";
            Regex rx = new Regex(@"\d+y");
            string[] splitedArray = SplitByRegex(sourceStr, rx);

            for (int i = 0; i < splitedArray.Length; i++)
            {
                Console.WriteLine(String.Format("'{0}'", splitedArray[i]));
            }

            Console.ReadLine();
        }

        public static string[] SplitByRegex(string input, Regex rx)
        {
            MatchCollection matches = rx.Matches(input);
            String[] outArray = new string[matches.Count];
            for (int i = 0; i < matches.Count; i++)
            {
                int length = 0;
                if (i == matches.Count - 1)
                {
                    length = input.Length - (matches[i].Index + matches[i].Length);
                }
                else
                {
                    length = matches[i + 1].Index - (matches[i].Index + matches[i].Length);
                }

                outArray[i] = matches[i].Value + input.Substring(matches[i].Index + matches[i].Length, length);
            }

            return outArray;
        }
    }
}

输出:

'1y 250 '
'2y 32% '
'3y otherjibberish'

“解决方案”7z文件:Q11438740ConApp.7z

答案 1 :(得分:0)

这实际上很简单......只是使用了Regex.Split()方法。