我有一个字符串:
Hello "quoted string" and 'tricky"stuff' world
想要得到去掉引号部分的字符串,例如:
Hello and world
有什么建议吗?
我有一个字符串:
Hello "quoted string" and 'tricky"stuff' world
想要得到去掉引号部分的字符串,例如:
Hello and world
有什么建议吗?
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
"\"[^\"]*\""
作为我的正则表达式字符串(即 "[^"]*"
作为正则表达式)。您能解释一下您的正则表达式是如何工作的以及为什么吗? - DomenicRegex.Replace()
方法进行模式匹配和替换。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();
}