我有一个字符串:
Hello“引用字符串”和“棘手”的东西'世界
并希望获取字符串减去引用的部分。如,
Hello and world
有什么建议吗?
答案 0 :(得分:8)
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
进入
Hello and world
答案 1 :(得分:1)
使用正则表达式将任何带引号的字符串与字符串匹配,并将其替换为空字符串。使用Regex.Replace()
方法进行模式匹配和替换。
答案 2 :(得分:0)
如果像我一样,你害怕正则表达式,我会根据你的示例字符串整理一个功能性的方法。可能有一种方法可以缩短代码,但我还没有找到它。
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();
}