MikeL
MikeL

Reputation: 161

Regular Expression - get value from string based on criteria

I have a string delimited with underscores:

id_name_type_environment

which would give me something like this:

basically based on the type I need to get the name. Rather than doing string parsing and substrings I would like to do this using a regex which would do If type = x then extract the name

Is there a simple regex way of doing this?

Upvotes: 0

Views: 135

Answers (2)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

        Regex regex = new Regex(".*_(.*)_x_.*");
        string incomingValue = @"123_NAME_x_dev";
        string inside = null;
        Match match = regex.Match(incomingValue);

        if (match.Success)
        {
            inside = match.Groups[1].Value;
        }

This should get the name if the type=x, you can change it to match type=y of course

Upvotes: 1

Jonny Piazzi
Jonny Piazzi

Reputation: 3784

Get the type like this:

var value = Regex.Match("123456_MyName_x_dev", @"(?<=^\w+_\w+_)\w+(?=_\w+$)").Value

And get name like this:

var value = Regex.Match("123456_MyName_x_dev", @"(?<=^\w+_)\w+(?=_\w+_\w+$)").Value

Upvotes: 0

Related Questions