kei
kei

Reputation: 20481

Regex to extract first instance of number and replace everything else in C#

I have a string that looks like:

/some/example/path/here/[somePositiveInteger]_.000

where [somePositiveInteger] is some positive integer (e.g. 1, 23542, 331232, etc.) and _.000 can be _.101, _.343, etc.

I'd like to change this to look something like:

/some/example/path/here/dispform.aspx?id=[somePositiveInteger]

I figured I could just extract [somePositiveNumber] by splitting the string on /, then removing _.000, then appending the number back to /some/example/path/here/dispform.aspx?id=.

However, this seems like something regex can do more efficiently. How do I do this using regex then?

Upvotes: 0

Views: 89

Answers (2)

Timwi
Timwi

Reputation: 66573

The following method produces the result you describe:

static string ConvertPath(string input)
{
    var match = Regex.Match(input, @"^(.*)/(\d+)_\.\d\d\d$");
    if (!match.Success)
        throw new ArgumentException("The input does not match the required pattern.");
    return match.Groups[1].Value + "/dispform.aspx?id=" + match.Groups[2].Value;
}

Note that it uses a regular expression to match the pattern, and then constructs a new string from the resulting match. It throws an exception if the input is not in the required form.

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Try with this example:

string input = "/some/example/path/here/99999_.000";
input = Regex.Replace(input, @"(.*/)(\d+)_\.\d{3}$", "$1"+"dispform.aspx?id=$2");

$1 holds the whole path before / for the regex (.*/)

$2 holds the required digit for the regex (\d+)

Upvotes: 1

Related Questions