0

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?

2 Answers 2

1

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+)

Sign up to request clarification or add additional context in comments.

1 Comment

Both solutions work for me, so I'll have to give it to who answered first in this case (: Thanks to you and @Timwi
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.