2010-08-04 97 views
2

我想在兩個':'字符之間分隔我的字符串。使用':'符號的正則表達式標識符和分隔符

例如,如果輸入是"mypage-google-wax:press:-happy",那麼我需要"press"

可以假定輸入不包含任何數字字符。

+0

爲什麼輸出是「新聞」?它究竟應該做什麼?你談論「分離」你的字符串,但不是你真正的意思是... – 2010-08-04 12:50:02

+0

(試圖清理問題,不知道如果我沒有意外改變它的意思。) – dtb 2010-08-04 12:54:53

回答

3

任何理由使用正則表達式的所有,而不只是:

string[] bits = text.Split(':'); 

這是假設我理解正確你的問題......我一點兒也不肯定。不管怎麼說,這取決於你真正想做的事,這可能對你有用...

1

如果你總是有一個字符串格式{stuffIDontWant}:{stuffIWant}:{moreStuffIDontWant}然後String.Split()是你的答案,而不是正則表達式。

要檢索中間值,你會怎麼做:

string input = "stuffIDontWant:stuffIWant:moreStuffIDontWant"; //get your input 
string output = ""; 
string[] parts = input.Split(':'); 
    //converts to an array of strings using the character specified as the separator 
output = parts[1]; //assign the second one 
return output; 

正則表達式是良好的百通匹配,但是,除非你專門找字pressString.Split()是這種需要一個更好的答案。

1

如果你想在正則表達式:

string pattern = ":([^:]+):"; 
    string sentence = "some text :data1: some more text :data2: text"; 
    foreach (Match match in Regex.Matches(sentence, pattern)) 
    Console.WriteLine("Found '{0}' at position {1}", 
         match.Groups[1].Value, match.Index); 
相關問題