As a human being, this seems like a very simple problem, but trying to get a
computer to understand what you want is another story. Let's look at an
example of why this is more complex of a problem, using the following string:
Meeting today : 10AM
This is an "example: 1"
Meeting tomorrow : 11AM
This is another "example: 2"
If I understand the requirements, the desired output should be:
Meeting today @ 10AM
This is an "example: 1"
Meeting tomorrow @ 11AM
This is another "example: 2"
Unfortunately, if we wrote a regular expression to replace any colon
) not
inside quotes, the colon before 11AM would not be changed, because there is a
preceding and following quote.
I've had a similar problem before as well, and the best solution I could
think of was to extract all of the quoted strings and replace them with an
escape sequence, then do the replacement, then re-inflate the escape
sequences with the extracted values.
An example would look something like:
string s = @"
Meeting today : 10AM
This is an ""example: 1""
Meeting tomorrow : 11AM
This is another ""example: 1""
";
// Extract the quoted strings
MatchCollection matches = Regex.Matches(s, @"""[^\""]+?""");
for(int x=matches.Count-1; x>-1; x--)
{
Match match = matches[x];
s = s.Remove(match.Index, match.Length);
s = s.Insert(match.Index, "{" + x + "}");
}
// Replace the remaining : with @
s = s.Replace(':', '@');
// Reinflate the escaped strings
for(int x=0; x<matches.Count; x++)
{
Match match = matches[x];
s = s.Remove(match.Index, x.ToString().Length + 2);
s = s.Insert(match.Index, match.Value);
}
If anyone else has a better solution, I'd love to hear it.
Hope this helps.