2017-04-05 102 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

相关问题