2011-11-07 107 views
0

我有這樣的字符串:一個行函數來替換字符在C#字符串

http://127.0.0.1:22/Test 

是否有可能使用,我可以使用,使刪除冒號和端口號正則表達式一些功能單一。

有人曾建議我使用下列但是這是給我的問題,如果CURRENTURL爲空!

var ip = new Uri((string)Session["CurrentUrl"]); 
var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery); 
return Session["CurrentUrl"] == null ? Home() : Redirect((string)ipNoPort); 

我真正需要的是一些方法,它結合了三條線並檢查null。

+4

爲什麼你需要他們在同一行?究竟會解決什麼問題?很可能你會得到一段很長且複雜的代碼,這些代碼很難調試。 – Oded

+0

事實上,就環繞代碼與空CURRENTURL會話變量的檢查。的 – Rickjaah

+1

可能重複[我怎樣才能從C#字符串中刪除一些字符?(http://stackoverflow.com/questions/7990920/how-can-i-remove-some-characters-from-ac-sharp-string) – V4Vendetta

回答

1

只是測試無效使用會話變量之前:

if(Session["CurrentUrl"] != null) 
{ 
    var ip = new Uri(Session["CurrentUrl"]); 
    var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery); 
    return Redirect(ipNoPort); 
} 

return Home(); 
0
url = Regex.Replace(url, @"^(http://([0-9]+\.?)+)(:[0-9]+)", "$1"); 
+0

感謝這個不錯 –

+0

這將打破,如果有一些「123」這不是描述的端口 - 例如就像'http://sample.com/post.asp?text =我的+電話:555-123'! – Mario

+0

@Mario發生了變化。 –

0

你不能做到這一切在同一行(你可以,但仍然沒有什麼區別代碼明智)。所以你不會首先檢查null。

要刪除的端口(不知道這是明智的,做的,取決於你的佈局):

string url = (string) Session["CurrentUrl"]; 
string clean_url = url != null ? Regex.Replace(url, "://([^/:]+:\\d+)", "://$1") : Home(); 
0

只是爲了一點點增加俄德的答案。

此以下行

var ip = new Uri((string)Session["CurrentUrl"]); 

將打破如果Session["CurrentUrl"]

  1. NULL(System.ArgumentNullException
  2. 不是字符串(System.InvalidCastException
  3. 不是包括空字符串的URL。 (System.UriFormatException

俄德的答案需要照顧的第一個也可能在你的代碼的異常的唯一可能的原因,但除非你能絕對確保其始終null或URL,那麼你可能會更好具有以下

var currentUrl = Session["CurrentUrl"] as string; 

if (!string.IsNullOrEmpty(currentUrl)) 
{ 
    try 
    { 
     var ip = new Uri(currentUrl); 
     var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery); 
     return Redirect(ipNoPort); 
    } 
    catch (System.UriFormatException) 
    { 
     return Home() 
    } 
} 
else 
{ 
     return Home(); 
} 

另一種選擇是隻趕上three exceptions at once但它更昂貴的,如果它發生了很多。

如果使用這個有很多它可能是值得創建一個UrlTryParse方法。