Click here to Skip to main content
15,881,644 members
Please Sign up or sign in to vote.
4.90/5 (12 votes)
I am using a Regex with a MatchEvaluator delegate to process a format string, e.g. "Time: %t, bytes: %b" would replace the "%t" with a time stamp, and the "%b" with a bytes count. Needless to say, there are loads of other options!
To do this, I use:
Regex regex = new Regex("%((?<BytesCompleted>b)|(?<BytesRemaining>B)|(?<TimeStamp>t))");
string s = "%bhello%t(HH:MM:SS)%P";
string r = regex.Replace(s, new MatchEvaluator(ReplaceMatch));
and
string ReplaceMatch(Match m)
    {
    ... Handle the match replacement.
    }

What would be nice is if I could use the Regex group name (or even the number, I'm not that fussy) in the delegate instead of comparing against the raw match to find out which match this is:
string ReplaceMatch(Match m)
    {
    ...
    case "%t":
    ...
    case "%b";
    ...
    }
Is pretty ugly; I would like to use
string ReplaceMatch(Match m)
    {
    ...
    case "BytesCompleted":
    ...
    case "TimeStamp":
    ...
    }
I can't see anything obvious via the debugger, or via google. Any ideas?
Posted

1 solution

I agree it would be nice to be able to use the group name in the switch; unfortunately the Group object doesn't have a Name property (and neither does its base class Capture) so the best you'll be able to do is the following:

string ReplaceMatch(Match m)
    {
    if (m.Groups["BytesCompleted"].Success) ...
    else if (m.Groups["BytesRemaining"].Success) ...
    ...
    }
 
Share this answer
 
v2
Comments
OriginalGriff 7-May-10 16:15pm    
That's what I figured; I was just hoping I'd missed something. Thank you for your help anyway!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900