如何从C#中的字符串中删除带引号的字符串文字?
我有一个字符串: 您好“引用字符串”和“棘手的”东西的世界 并希望返回字符串减去引用部分。例如 你好,世界如何从C#中的字符串中删除带引号的字符串文字?,c#,algorithm,string,C#,Algorithm,String,我有一个字符串: 您好“引用字符串”和“棘手的”东西的世界 并希望返回字符串减去引用部分。例如 你好,世界 有什么建议吗?使用正则表达式将任何带引号的字符串与字符串匹配并替换为空字符串。使用Regex.replace()方法进行模式匹配和替换 resultString = Regex.Replace(subjectString, @"([""'])# Match a quote, remember which one (?: # Then... (?!\1)
有什么建议吗?使用正则表达式将任何带引号的字符串与字符串匹配并替换为空字符串。使用
Regex.replace()
方法进行模式匹配和替换
resultString = Regex.Replace(subjectString,
@"([""'])# Match a quote, remember which one
(?: # Then...
(?!\1) # (as long as the next character is not the same quote as before)
. # match any character
)* # any number of times
\1 # until the corresponding closing quote
\s* # plus optional whitespace
",
"", RegexOptions.IgnorePatternWhitespace);
我会用你的例子
resultString = Regex.Replace(subjectString,
@"([""'])# Match a quote, remember which one
(?: # Then...
(?!\1) # (as long as the next character is not the same quote as before)
\\?. # match any escaped or unescaped character
)* # any number of times
\1 # until the corresponding closing quote
\s* # plus optional whitespace
",
"", RegexOptions.IgnorePatternWhitespace);
还将处理转义引号
因此,它将正确地转换
Hello "quoted \"string\\" and 'tricky"stuff' world
进入
如果你和我一样害怕正则表达式,我已经根据你的示例字符串组合了一种函数式的方法来实现它。可能有一种方法可以使代码更短,但我还没有找到
private static string RemoveQuotes(IEnumerable<char> input)
{
string part = new string(input.TakeWhile(c => c != '"' && c != '\'').ToArray());
var rest = input.SkipWhile(c => c != '"' && c != '\'');
if(string.IsNullOrEmpty(new string(rest.ToArray())))
return part;
char delim = rest.First();
var afterIgnore = rest.Skip(1).SkipWhile(c => c != delim).Skip(1);
StringBuilder full = new StringBuilder(part);
return full.Append(RemoveQuotes(afterIgnore)).ToString();
}
private静态字符串RemoveQuotes(IEnumerable输入)
{
字符串部分=新字符串(input.TakeWhile(c=>c!='''''''''&&c!='\'''''.ToArray());
var rest=input.SkipWhile(c=>c!='''”&&c!='\'';
if(string.IsNullOrEmpty(新字符串(rest.ToArray()))
返回部分;
char delim=rest.First();
var afterIgnore=rest.Skip(1).SkipWhile(c=>c!=delim.Skip(1);
StringBuilder full=新的StringBuilder(零件);
返回full.Append(RemoveQuotes(afterIgnore)).ToString();
}
OK,所以带引号的字符串可以包含“其他”引号符号。是否也可以有转义引号,如“这是一个”字符串“
?是否需要支持转义引号字符?而且,这似乎是一个无用的练习——这应该被标记为家庭作业吗?@Kirk,我37岁了,很久以前就放弃了家庭作业。对不起,如果我的问题不符合你的高标准,那“不要阻止believin,抓住街灯人的感觉”呢?“believin”和“feelin”上缺少的gs是否被视为内部引用?“不要”中的撇号呢?还有,你需要考虑“圆引号”还是“直引号”?我的建议是:在编写任何代码之前,先写一份非常仔细和详细的规范。@Andrew White:在你的例子中,引号是不平衡的。我只是用var“\”[^\“]*\”
作为我的正则表达式字符串(即,“[^”]*”
作为正则表达式)。你能解释一下你的孩子在做什么以及为什么吗?
private static string RemoveQuotes(IEnumerable<char> input)
{
string part = new string(input.TakeWhile(c => c != '"' && c != '\'').ToArray());
var rest = input.SkipWhile(c => c != '"' && c != '\'');
if(string.IsNullOrEmpty(new string(rest.ToArray())))
return part;
char delim = rest.First();
var afterIgnore = rest.Skip(1).SkipWhile(c => c != delim).Skip(1);
StringBuilder full = new StringBuilder(part);
return full.Append(RemoveQuotes(afterIgnore)).ToString();
}