I wasn't able to do it in one pass, but this solution seems to work:
// call the AddAnds() method with your input text
const string quotedTextFinderPattern = @"
(?<quote>"")
(?<quotedText>.*?)
\k<quote>
";
const string wordFinderPattern = @"(?<word>\s+\w+)";
Regex wordFinder = new Regex(wordFinderPattern,
RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
public string AddAnds(string input)
{
return Regex.Replace(input, quotedTextFinderPattern,
new MatchEvaluator(this.AndInserter),
RegexOptions.IgnorePatternWhitespace);
}
private string AndInserter(Match match)
{
string quotedText = match.Groups["quotedText"].Value;
return "\"" +
wordFinder.Replace(quotedText,
new MatchEvaluator(this.IgnoreAnds))
+ "\"";
}
private string IgnoreAnds(Match match)
{
string word = match.Groups["word"].Value;
if (String.Compare(word, " and", true) != 0)
{
return " and" + word;
}
else
{
return String.Empty;
}
}
Craig wrote:
Hi
I'm having some troubles getting my regex to work. I have a string as follows
The "quick and brown" fox "jumped over the" lazy dog.
The output should be as follows:
The "quick and brown" fox "jumped and over and the" lazy dog.
So the expression needs to insert 'and' between the groups of words enclosed
in double quotes, ignoring the insert if the 'and' word exists bewteen the
quotes.
If anyone has some ideas how to do this, I would be very greatful.