How can I replace ending of a string using regex?

I have a string "http://www.something.com/test/?pt=12"

I want to replace pt=12 by pt=13 using regex.

The string after replace will be : "http://www.something.com/test/?pt=13"

How can I achieve this in C#?

Upvotes: 1

Views: 54

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626804

I suppose you know the pt= part. I also presume that the param value is a number.

Then, you can use the following regex replacement:

var newval = 13;
var res = Regex.Replace(str, @"\?pt=[0-9]+", string.Format("?pt={0}", newval));

If the param can be non-first in the query string, replace \? with [?&].

Note that you could use the System.UriBuilder class. It has a Query property that you can use to rebuild the query string.

Upvotes: 1

Ralph
Ralph

Reputation: 3029

string result = "";
Regex reg = new Regex("(.*)(pt=12)");
Match regexMatch = reg.Match("http://www.something.com/test/?pt=12");
if(regexMatch.Success){
    result = regexMatch.Groups[1].Value + "pt=13"
}

Upvotes: 1

Related Questions