2017-04-05 100 views
0

我要全部更換分號括在引號用空間。我如何在C#中做到這一點?正則表達式替換分號之間引號C#

例如:

這個字符串:

this is an example; "this is other ; example"

將返回:

this is an example; "this is other example"

我在等待着您的幫助!

+2

是否有你的字符串逃過任何序列?像'\\''爲反斜槓和'\''爲雙引號?如果是CSV,也許一個CSV解析器比用雙引號替換';'更合適? http://stackoverflow.com/questions/6542996/how-to-split-csv-whose-columns-may-contain/6543418#6543418)。 –

+0

是的,它是一個.csv文件,我會考慮使用解析器,謝謝 –

回答

4

試試這個:

string input = "this is an example; \"this is other ; example\""; 
var regex = new Regex("\\\"(.*?)\\\""); 
var output = regex.Replace(input, m => m.Value.Replace(";"," ")); 
+1

您的意思是'm.Value.Replace(';','')'?因爲你有什麼不會編譯的,你也忘記了'input'字符串的雙引號。 – juharr

+0

是的,代碼現在已經更新了 –

+0

Still它不應該編譯,它應該是'string input =「這是一個例子; \「這是其他的;例子\」;'和你爲什麼要在OP表示他們想要一個空間時用符號代替分號? – juharr

0

編輯:這將工作。

string yourString = "hello there; \"this should ; be replaced \""; 

string fixedString = Regex.Replace(yourString, "(\"[^\",]+);([^\"]+\")", delegate (Match match) 
{ 
    string v = match.ToString(); 
    return v.Replace(";", " "); 
}); 
+0

修改用空格代替 – justiceorjustus

+0

對我有用,謝謝! –

+1

這對於字符串不起作用像''這是一個例子; 「這是其他」; \「example \」「'因爲它會刪除第二個分號。 – juharr

-2

嘗試以下操作:

string input = "this is an example; \"this is other ; example\""; 
      string pattern = "\"(?'prefix'[^;]+);(?'suffix'[^\"]+)\""; 

      string output = Regex.Replace(input,pattern,"\"${prefix} ${suffix}\""); 
+0

我剛剛試過這個,它也刪除了雙引號。 – juharr

+0

這個例子是刪除引號 –

+0

加回引號 – jdweng

相關問題