替换字符串中的字符,但双引号内的值除外

时间:2014-01-24 08:29:14

标签: c#-4.0

我想用空格替换一个字符数组,除了字符串中双引号内的值。

示例

"India & China" relationship & future development

在上面的示例中,我需要替换&,但不在任何双引号("")内。预期结果应为

结果

"India & China" relationship  future development

其他字符串示例

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.

到目前为止,我已完成以下逻辑来替换字符串中的字符。

代码

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;

1 个答案:

答案 0 :(得分:3)

这是使用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();