I was wondering how do I use regex to replace string between two characters.
var oldString = "http://localhost:61310/StringtoConvert?Id=1"
Expected result = "http://localhost:61310/ConvertedString?Id=1"
I was wondering how do I use regex to replace string between two characters.
var oldString = "http://localhost:61310/StringtoConvert?Id=1"
Expected result = "http://localhost:61310/ConvertedString?Id=1"
No need for regex or string operations, use UriBuilder class.
var oldString = "http://localhost:61310/StringtoConvert?Id=1";
var newuri = new UriBuilder(new Uri(oldString));
newuri.Path = "ConvertedString";
var result = newuri.ToString();
You can use Regex.Replace(string, string, string)
. So, if you want to replace a substring between a /
and a ?
, you can use
string result = Regex.Replace(oldString, "(?<=\/)[^\?]*(?=\?)", "ConvertedString");
?<=
is a lookbehind, \/
escapes the slash character, [^\?]*
matches any characters not a ? any number of times, ?=
is a lookahead, and \?
escapes the question mark character.
Instead of Regex, you can use the System.Uri
class then concatenate or interpolate your new value:
private static string ReplacePath(string url, string newPath)
{
Uri uri = new Uri(url);
return $"{uri.GetLeftPart(UriPartial.Authority)}/{newPath}{uri.Query}";
}
Calling this method with your url, and the new path (ie "ConvertedString") will result in the output: "http://localhost:61310/ConvertedString?Id=1"
Fiddle here.
EDIT
@Eser's answer is way better than mine. Did not know that class existed. Mark their answer as the right one not mine.