-4

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"

code4life
  • 15,655
  • 7
  • 50
  • 82
  • 1
    Did you try anything? Look at any documentation for how to use regex? – mason Oct 06 '17 at 20:05
  • Possible [this](https://stackoverflow.com/questions/6619398/match-a-regex-and-reverse-the-matches-within-the-target-string) helps –  Oct 06 '17 at 20:08
  • I would like to thank you all for help. I have implemented private static string ReplacePath(string url, string newPath) { Uri uri = new Uri(url); return $"{uri.GetLeftPart(UriPartial.Authority)}/{path}{uri.Query}"; } and it works – Ashish Parajuli Oct 06 '17 at 20:32
  • 1
    @AshishParajuli use Eser's solution, its way better than mine. Also mark their answer as the correct one – maccettura Oct 06 '17 at 20:32

3 Answers3

3

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();
Eser
  • 12,346
  • 1
  • 22
  • 32
1

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.

zambonee
  • 1,599
  • 11
  • 17
  • `string result = Regex.Replace(oldString, "(http\:\/\/localhost\:61310\/)(\w+)(\?Id\=1)", "$1ConvertedString$3");` – Tiramonium Oct 06 '17 at 20:13
1

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.

maccettura
  • 10,514
  • 3
  • 28
  • 35