2012-03-22 95 views
2

我需要更換,除非我的字符串與破折號字符和數字錯誤的符號錯誤的符號「 - 」正則表達式替換C#

var myString = "this=is+/* [email protected]# string^&*("; 

我用

Regex.Replace(myString, "[^0-9a-zA-Z]+", "-"); 

,因此它是「這個-is ---- ----錯誤字符串----」

但我需要‘這 - 是 - 錯串’

我應該改變我我的RegEx。謝謝!

+1

無法重現。 Expresso提供正確的輸出。在運行'Replace'之前,你還做了其他的事情嗎? – Shimrod 2012-03-22 10:59:26

+0

用expresso試了一下。我得到{this-is-wrong-string-}作爲輸出,這看起來是正確的給你的正則表達式。 – Gishu 2012-03-22 11:00:13

+0

我已經試過你的示例代碼,結果是你需要用一個短劃線。 – 2012-03-22 11:01:02

回答

4

無法重現:

using System; 
using System.Text.RegularExpressions; 

class Test 
{ 
    static void Main() 
    { 
     var input = "this=is+/* [email protected]# string^&*("; 
     var output = Regex.Replace(input, "[^0-9A-Za-z]+", "-"); 
     Console.WriteLine(output); 
    }     
} 

輸出:this-is-wrong-string-

所以,你可能需要使用TrimEnd('-')擺脫尾隨的「 - 」,但除此之外,它看起來好像沒什麼問題。比較你的代碼和我的簡短但完整的程序,如果你找不到有什麼問題,拿出一個類似的簡短但完整的程序,其中顯示的問題。

2

你的正則表達式的工作對我來說:

PS> "this=is+/* [email protected]# string^&*(" -replace '[^0-9a-zA-Z]+','-' 
this-is-wrong-string- 

但是,你需要刪除尾隨其後-