PaulH
PaulH

Reputation: 7843

string macro replacement

I have a Visual Studio 2008 C# .NET 3.5 application where I need to parse a macro.

Given a serial serial number that is N digits long, and a macro like %SERIALNUMBER3%, I would like this parse method to return only the first 3 digits of the serial number.

string serialnumber = "123456789";
string macro = "%SERIALNUMBER3%";
string parsed = SomeParseMethod(serialnumber, macro);

parsed = "123"

Given `%SERIALNUMBER7%, return the first 7 digits, etc..

I can do this using String.IndexOf and some complexity, but I wondered if there was a simple method. Maybe using a Regex replace.

What's the simplest method of doing this?

Upvotes: 0

Views: 1700

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124622

var str = "%SERIALNUMBER3%";
var reg = new Regex(@"%(\w+)(\d+)%");
var match = reg.Match( str );
if( match.Success )
{
    string token = match.Groups[1].Value;
    int numDigits = int.Parse( match.Groups[2].Value );
}

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

Very quick and dirty example:

static void Main(string[] args)
        {
            string serialnumber = "123456789";
            string macro = "%SERIALNUMBER3%";

            var match = Regex.Match(macro, @"\d+");

            string parsed = serialnumber.Substring(0, int.Parse(match.ToString()));
        }

Upvotes: 0

qJake
qJake

Reputation: 17119

Use the Regex class. Your expression will be something like:

@"%(\w)+(\d)%"

Your first capture group is the ID (in this case, "SERIALNUMBER"), and your second capture group is the number of digits (in this case, "3").

Upvotes: 0

Related Questions