正则表达式只替换特定的字符集

时间:2017-03-09 13:36:08

标签: c# asp.net regex asp.net-mvc razor

我有这样的字符串:

Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap

注意标志:

"

and

'

我想用这样的单引号替换它们:

'

我试过这个正则表达式:

Regex.Replace(inputText, @"(\s+|"|')", "'")

但是我得到的结果并不是我想要的...我怎样才能删除单引号的特定字符集,就像我上面显示的那样?

编辑家伙这是输入:

Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap

2 个答案:

答案 0 :(得分:3)

您不需要更换空间,因此您的模式应该是:

@"("|')"

在代码中(你也应该将结果存储在某个变量中):

var str = "Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap";
var res = Regex.Replace(inputText, @"("|')", "'")

此外,您可以在没有正则表达式的情况下进行替换:

var str = "Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap";
str = str.Replace(""", "'");
str = str.Replace("'", "'");

答案 1 :(得分:3)

您可以使用WebUtility.HtmlDecode中的System.Net方法。

var result = WebUtility.HtmlDecode("Small Bubble Roll 3/16" x 1400' x 12" Perforated 3/16 Bubbles 1400 Sq Ft Wrap");

结果输出:

  

小气泡卷3/16“x 1400'x 12”穿孔3/16气泡1400平方英尺包装