我想用空白替换字符数组,除了字符串中双引号内的值。
例子
"India & China" relationship & future development
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我需要替换&,但它不在任何双引号("")内。预期结果应该是
结果
"India & China" relationship future development
Run Code Online (Sandbox Code Playgroud)
字符串的其他示例
relationship & future development "India & China" // Output: relationship future development "India & China"
"relationship & future development India & China // Output: reflect the same input string as result string when the double quote is unclosed.
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经完成了以下逻辑来替换字符串中的字符。
代码
string invalidchars = "()*&;<>";
Regex rx = new Regex("[" + invalidchars + "]", RegexOptions.CultureInvariant);
string srctxtaftrep = rx.Replace(InvalidTxt, " ");
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
srctxtaftrep = regex.Replace(srctxtaftrep, @" ");
InvalidTxt = srctxtaftrep;
Run Code Online (Sandbox Code Playgroud)
这是一种使用应该有效的非正则表达式方法StringBuilder:
string input = "\"India & China\" relationship & future development";
HashSet<char> invalidchars = new HashSet<char>("()*&;<>");
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
foreach(char c in input)
{
if(c == '"') inQuotes = !inQuotes;
if ((inQuotes && c != '"') || !invalidchars.Contains(c))
sb.Append(c);
}
string output = sb.ToString();
Run Code Online (Sandbox Code Playgroud)