1

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#?

4
  • Unfortunately links are not working.. Commented Jul 30, 2015 at 4:43
  • 5
    You could just use the String.Replace() method: myStr.Replace("pt=12", "pt=13"). Commented Jul 30, 2015 at 5:45
  • Spencer - I know the string.replace but actual requirmwent is quite complex.. I need a regex only. It's not a simple string replace. Commented Jul 30, 2015 at 6:17
  • If my answer was the answer you were looking for, could you please give it a check. thanks :) Commented Jul 30, 2015 at 22:50

2 Answers 2

1
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"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.