DonMax
DonMax

Reputation: 960

Replace Characters in a string except values inside double quote

I want to replace an array of characters with empty space except values inside double quote in a string.

Example

"India & China" relationship & future development

In the above example, I need to replace & but thats not inside any of the double quotes(""). The expected result should be

Result

"India & China" relationship  future development

Other Examples of String

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.

I have so far done the below logic to replace the characters in a string.

Code

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;

Upvotes: 3

Views: 1179

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

Here's a non-regex approach using a StringBuilder which should work:

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();

Upvotes: 5

Related Questions