我正在尝试在一些格式不一致的HTML上进行匹配,并且需要去除一些双引号。
当前:
<input type="hidden">
目标:
<input type=hidden>
这是错误的,因为我没有正确转义:
s = s.Replace(“”“,”“);
这是错误的,因为(据我所知)没有空白字符:
s = s.Replace('"', '');
用空字符串替换双引号的语法/转义字符组合是什么?
Answers:
您可以使用以下任一方法:
s = s.Replace(@"""","");
s = s.Replace("\"","");
...但是我确实对您为什么要这么做感到好奇?我认为保持属性值被引用是一种好习惯?
c#"\""
:,因此s.Replace("\"", "")
vb / vbs / vb.net:""
因此s.Replace("""", "")
这对我有用
//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;
如果您只想从字符串的末尾(而不是中间)除去引号,则字符串的两端都有可能存在空格(例如,解析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)
如果您想删除单个字符,我想简单地读取数组并跳过该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('"');