RegExp具有更好的结果

时间:2016-01-14 22:29:30

标签: c# regex

string STR = "The Quick Brown Fox Jumps";
string PTR = "[A-Z][a-z]+ [A-Z][a-z]+";
MatchCollection MCZ = Regex.Matches( STR, PTR ) ;   
if ( MCZ.Count > 0 )        
{
    string RTN ="";
    foreach ( Match x in MCZ )
    RTN += x.Value + "\n" ;
    MessageBox.Show( RTN );
}
else
    MessageBox.Show("Noop");

...您好 我的结果是这样的;

The Quick
Brown Fox

但是,我想拥有;

The Quick
Quick Brown
Brown Fox
Fox Jumps

很好的提示,请!!

问候。

2 个答案:

答案 0 :(得分:0)

正如我所说,还有更好的方法......

using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        string str = "The Quick Brown Fox Jumps";

        string result = "";

        var tokens = str.Split(' ');

        for(int i = 0; i < tokens.Length - 1; i += 1) {
            result += tokens[i] + ' ' + tokens[i + 1] + "\n";
        }

        Console.WriteLine(result);
    }
}

答案 1 :(得分:0)

尝试:     (?<=(?<v>\w+)\s+)(?<v>\w+)

我无法将直接结果链接到regexstorm.net(因为有些括号不起作用?!?!?)但是在http://regexstorm.net/tester上试用

请参阅表格。每个匹配包含两个组v的捕获。

SAMPLE

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var input = "The Quick Brown Fox Jumps";

        var regex = new Regex(@"(?<=(?<v>\w+)\s+)(?<v>\w+)");
        foreach (var match in regex.Matches(input).Cast<Match>())
        {
            var value = string.Join(" ", match.Groups["v"].Captures.Cast<Capture>().Select(x => x.Value));

            Console.WriteLine(value);
        }
    }
}

输出将按预期进行。