从.NET中的字符串中去除双引号


100

我正在尝试在一些格式不一致的HTML上进行匹配,并且需要去除一些双引号。

当前:

<input type="hidden">

目标:

<input type=hidden>

这是错误的,因为我没有正确转义:

s = s.Replace(“”“,”“);

这是错误的,因为(据我所知)没有空白字符:

s = s.Replace('"', '');

用空字符串替换双引号的语法/转义字符组合是什么?

Answers:


213

我认为您的第一行实际上可以工作,但我认为您需要为包含一个单引号的字符串(至少在VB中)使用四个引号:

s = s.Replace("""", "")

对于C#,您必须使用反斜杠转义引号:

s = s.Replace("\"", "");

1
如果字符串中包含更多的引号,则会产生副作用
Aadith Ramia

28

我还没有看到我的想法重复出现,所以我建议您string.Trim在Microsoft文档中查看有关C#的信息,您可以添加要修剪的字符,而不是简单地修剪空白:

string withQuotes = "\"hellow\"";
string withOutQotes = withQuotes.Trim('"');

应该导致withOutQuotes被"hello"代替""hello""


26
s = s.Replace("\"", "");

您需要使用\来转义字符串中的双引号字符。


2
如果字符串中包含更多的嵌入引号,则会产生副作用
Aadith Ramia

14

您可以使用以下任一方法:

s = s.Replace(@"""","");
s = s.Replace("\"","");

...但是我确实对您为什么要这么做感到好奇?我认为保持属性值被引用是一种好习惯?


1
我正在使用HTML Agility Pack查找特定链接,然后需要从HTML文本中删除该链接中的值。HTML Agility Pack引用属性值,但不引用原始HTML。(所有这些都用于一项测试。)
甚至Mien

如果字符串中包含更多的嵌入引号,则会产生副作用
Aadith Ramia


5

c#"\"":,因此s.Replace("\"", "")

vb / vbs / vb.net:""因此s.Replace("""", "")


如果字符串中包含更多的引号,则会产生副作用
Aadith Ramia



1

这对我有用

//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);

//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;

1

如果您只想从字符串的末尾(而不是中间)除去引号,则字符串的两端都有可能存在空格(例如,解析CSV格式的文件,该字符串后面有一个空格逗号),那么您需要调用Trim函数两次 ...例如:

string myStr = " \"sometext\"";     //(notice the leading space)
myStr = myStr.Trim('"');            //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"');     //(would get what you want: sometext)

0
s = s.Replace( """", "" )

放在字符串中时,两个引号彼此相邻将充当预期的字符。


1
如果字符串中包含更多的引号,则会产生副作用
Aadith Ramia

0

如果您想删除单个字符,我想简单地读取数组并跳过该char并返回数组会更容易。我在自定义解析vcard的json时使用它。因为它是带有“带引号”文本标识符的错误json。

将以下方法添加到包含扩展方法的类中。

  public static string Remove(this string text, char character)
  {
      var sb = new StringBuilder();
      foreach (char c in text)
      {
         if (c != character)
             sb.Append(c);
      }
      return sb.ToString();
  }

然后,您可以使用以下扩展方法:

var text= myString.Remove('"');
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.