youwhut
youwhut

Reputation: 948

.NET Regular Expression - Create string?

I have a regular expression which I use to extract two portions of a folder name:

([0-9]{8})_([0-9A-Ba-c]+)_BLAH

No problems. This will match 12345678_abc_BLAH - I have "12345678" and "abc" in two groups.

Is it possible to construct the folder name by supplying a method with two strings and inserting them into the groups of the pattern?

public string ConstructFolderName(string firstGroup, string secondGroup, string pattern)
{

    //Return firstGroup_secondGroup_BLAH

}

This would be more manageable using same pattern to extract groups and construct strings.

Upvotes: 5

Views: 2430

Answers (2)

Shibumi
Shibumi

Reputation: 1399

If you know that your regex will always have two capturing groups, then you can regex the regex, so to speak.

private Regex captures = new Regex(@"\(.+?\)");

public string ConstructFolderName(string firstGroup, string secondGroup, string pattern)
{
    MatchCollection matches = captures.Matches(pattern);

    return pattern.Replace(matches[0].Value, firstGroup).Replace(matches[1].Value, secondGroup);
}

Obviously this doesn't have any error checking and might be better done with some other method than String.Replace; but, this certainly works and should give you some ideas.

EDIT: An obvious improvement would be to actually use the pattern to validate the firstGroup and secondGroup strings before you construct them. The MatchCollection's 0 and 1 item could create their own Regex and perform a match there. I can add that if you want.

EDIT2: Here's the validation I was talking about:

private Regex captures = new Regex(@"\(.+?\)");

public string ConstructFolderName(string firstGroup, string secondGroup, string pattern)
{
    MatchCollection matches = captures.Matches(pattern);

    Regex firstCapture = new Regex(matches[0].Value);

    if (!firstCapture.IsMatch(firstGroup))
        throw new FormatException("firstGroup");

    Regex secondCapture = new Regex(matches[1].Value);

    if (!secondCapture.IsMatch(secondGroup))
        throw new FormatException("secondGroup");

    return pattern.Replace(firstCapture.ToString(), firstGroup).Replace(secondCapture.ToString(), secondGroup);
}

Also, I might add that you can change the second capturing group to ([0-9ABa-c]+) since A to B isn't really a range.

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166446

Are you looking to use String.Format?

String.Format Method (String, Object[])

Upvotes: 4

Related Questions