Suppose I have a regex pattern and I want to replace the matches of the pattern with something else. In the current pattern there are two groups that will match and each one is numbered ($1 and $2):
Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\^=([^\]]+)\]");
string replacement = "[starts-with(@$1,$2)]";
Example CSS Selector:
[id^="blah"]
Expected output:
[start-swith(@ID,"blah")] // Note ID is capitalized
Here is another regex pattern:
Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\*=([^\]]+)\]");
string replacement = "[contains(@$1,$2)]");
When I’m performing the replace, is there any way to capitalize the matches in group $1?
Note: I have numerous patterns that get added to a list and they’re paired with their replacement string, so I have to make the solution works for all of the replacements which require capitalization of some of the matching groups.
Update
I think I just thought of a possible solution: convert the replacement string to a MatchEvaluator and return the capitalized group matches when needed. I think this might work:
Regex pattern = new Regex(@"\[([a-zA-Z0-9_\-]+)\^=([^\]]+)\]");
MatchEvaluator evaluator = new MatchEvaluator((Match m) =>
{
return string.Format("[starts-with(@{0},{1})]", m.Groups[1].Value.ToUpper(), m.Groups[2].Value);
});
If anybody can think of a better solution, then please let me know. Greatly appreciated!
MatchEvaluator is fine, think you burned me 😉 Anyway :