0

我有一个这样的字符串:

Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323

对于那些没有注意到的人,我想保留的文字总是介于/D和之间/p。我尝试使用正则表达式对其进行解析,但无法对所有字符串进行解析。它总是保留第一个或最后一个词。

如何保留一个新字符串,其中包含前一个字符串之间的所有/D单词/p

预期输出:

hello good
4

3 回答 3

6
string input = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
var parts = Regex.Matches(input, "/D(.+?)/p")
                 .Cast<Match>()
                 .Select(m => m.Groups[1].Value)
                 .ToList();

string finalStr = String.Join(" ", parts); //If you need this.
于 2012-11-01T22:53:23.787 回答
1

试试这个:

    string str = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
    Regex reg = new Regex(@"/D(\w+)/p");
    MatchCollection matches = reg.Matches(str);
    string result = "";
    foreach (Match match in matches)
    {
        result += match.Result("$1") + " ";
    }
    Console.WriteLine(result);  

或者:

    string str = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
    Regex reg = new Regex(@"(?!/D)[^D]\w+(?=/p)");
    MatchCollection matches = reg.Matches(str);
    string result = "";
    foreach (Match match in matches)
    {
        result += match.Value + " ";
    }
    Console.WriteLine(result);
于 2012-11-02T02:00:59.063 回答
1
var result = input.Split(new[] {"/D", "/p"}, 
                              StringSplitOptions.RemoveEmptyEntries)
                  .Where((w, i) => (i & 1) == 1);
于 2012-11-02T03:07:34.507 回答