2009-07-24 170 views
60

我试图匹配一些格式不一致的HTML,并且需要去掉一些双引号。从.NET中的字符串去除双引号

电流:

<input type="hidden"> 

目标:

<input type=hidden> 

这是错误的,因为我不是逃避它正确:

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

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

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

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

+2

您已经标记了这个C#和VB.NET。答案取决于它是哪一个。虽然大多数人都假设它是C#(像往常一样在这里),你接受的答案是C#。 – MarkJ 2009-07-24 16:42:30

+0

你说服我改变我接受的答案。 – 2009-07-24 17:22:05

回答

154

我觉得你的第一行会实际工作,但我认为你需要包含一个一个串的四个引号(在VB中至少):

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

为C#你必须用一个反斜杠逃脱引号:

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

中存在更多嵌入式引号,则会产生副作用,用于读取标记并为** ** C#和VB.NET回答+1 ,不像大多数人:) – MarkJ 2009-07-24 16:45:15

+0

这有一个副作用,如果有更多的嵌入式报价在字符串 – Aadith 2017-10-24 00:10:17

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

您需要使用\逃脱字符串中的双引号字符。

+0

如果在字符串 – Aadith 2017-10-24 00:09:33

3

您必须使用反斜杠来避免双引号。

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

中有更多嵌入式引号,则这会产生副作用,如果字符串 – Aadith 2017-10-24 00:09:14

5
s = s.Replace("\"",string.Empty); 
+0

这有一个副作用,如果有更多的嵌入式报价字符串 – Aadith 2017-10-24 00:09:07

12

您可以使用以下两种:

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

...但我确实很好奇,为什么你会这样做?我认为这是保持属性值引用的好习惯吗?

+0

借调这个问题...我想知道作为好。 – JAB 2009-07-24 14:31:44

+1

我正在使用HTML Agility Pack来查找某个链接,然后我需要从HTML文本中删除该链接中的值。 HTML Agility Pack会引用属性值,但原始HTML不会被引用。 (所有这一切都是为了一次测试。) – 2009-07-24 14:31:54

3

C#:"\"",从而s.Replace("\"", "")

VB/VBS/vb.net:""从而s.Replace("""", "")

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

两个引号彼此相邻的意志功能作为预期“字符时的字符串的内部。

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; 
8

我没有看到我的想法已经重复的,所以我会建议你看看string.Trim为C#的微软文档中,你可以添加一个字符来代替修整简单地修剪空的空间:

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

应导致withOutQuotes为"hello",而不是""hello""

0

如果您只想删除字符串末尾的引号(而不是中间字符),并且字符串两端可能有空格(即,解析CSV格式文件那里是逗号后面有一个空格),那么你就需要调用修正功能两次 ...例如:

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)