If I have input string in C#, how can I do series of Regex / linq operations on it to do Regex match on one piece of string and then another Regex on all pieces of string which are not matched by 1st Regex.
In other words, for input string:
<!-- Lorem ipsum dolor sit amet, consectetur adipiscing elit -->
<!-- The quick brown fox jumps over the lazy dog -->
Lorem ipsum dolor sit amet, consectetur adipiscing elit
The quick brown fox jumps over the lazy dog
<!-- Lorem ipsum dolor sit amet, consectetur adipiscing elit -->
<!-- The quick brown fox jumps over the lazy dog -->
Lorem ipsum dolor sit amet, consectetur adipiscing elit
The quick brown fox jumps over the lazy dog
I want to use Regex1 to match lines with <!-- --> and do certain operation on them without parsing them further. And to have Regex2 to match things in pieces of string not matched with Regex1, for example to find all words “fox” and “dog” in those lines and do certain operations on those words.
What is the best way to combine Regex/linq operations in situation like this?
You’re in luck since .NET supports variable-length lookbehind.
Therefore, you can use two regexes in sequence.
First, use
to find all comment lines. Backreference
$1will contain whatever is between the delimiters. For example:Second, to find and manipulate “dog” and “fox” in the other lines, you can use
What this regex means is “Match
dogorfoxunless the line starts with<!--“. So if you want to replace them, say, by “cat”, use