2011-12-16 123 views
1

是否可以使用String.Split而不切割字符串分隔符?String.Split cut separator

比如我有串

convertSource = "http://www.domain.com http://www.domain1.com"; 

我想建立陣列,並使用下面

convertSource.Split(new[] { " http" }, StringSplitOptions.RemoveEmptyEntries) 

我得到這樣的陣列碼

[1] http://www.domain.com 
[2] ://www.domain1.com 

我想保持HTTP,它似乎String.Split不僅單獨的字符串,而且還切斷分隔符。

+4

,但是你應該空間「分裂」不是HTTP,有何幫助? – 2011-12-16 13:17:09

+3

如果URL本身包含「http」會怎麼樣?像`http:// www.http.com /`。您應該首先定義明確的規則,限制可以作爲您的輸入的內容。 – 2011-12-16 13:19:06

回答

4

這是尖叫正則表達式:

Regex regEx = new Regex(@"((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)"); 
Match match= regEx.Match("http://www.domain.com http://www.domain1.com"); 

IList<string> values = new List<string>(); 
while (match.Success) 
{ 
    values.Add(match.Value); 
    match = match.NextMatch(); 
} 
1

這是因爲您使用" http"作爲分隔符。

試試這個:

string separator = " "; 
convertSource.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 

分割方法的工作方式,當它涉及到隔膜你提供給它砍下那裏,並從字符串也分隔。

從你想做的事有other ways分割字符串保持分隔符,然後如果你只是想去掉開頭或結尾,從您的字符串中的空格,然後我還是執意建議您使用.Trim()方法,你在說什麼:convertSource.Trim()

2
string[] array = Regex.Split(convertSource, @"(?=http://)");