2012-11-01 36 views
0

我有一個這樣的字符串:解析字符串與正則表達式

Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323 

對於那些誰沒有注意到,我想保持文本始終是/D/p之間。 我試圖解析它使用正則表達式,但我不能這樣做的所有字符串。 它始終保持第一個或最後一個單詞。

如何保留一個新的字符串,其中包含/D/p之間的所有單詞?

預期輸出:

hello good 

回答

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); 
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. 
+3

這裏的關鍵是,非貪婪量詞'+? '。沒有它,它會匹配'Hello/p2324141142DsddDsdsds/Dgood'。 –

1
var result = input.Split(new[] {"/D", "/p"}, 
           StringSplitOptions.RemoveEmptyEntries) 
        .Where((w, i) => (i & 1) == 1);