NachoDawg NachoDawg - 1 month ago 10
C# Question

replace a part of string. Characters to replace of unknown size

So I don't know a lot of c#, I have a javascript background.

I got a string.

String Url = Adress + "?station_ids=1322&observation_source=3&starttime=[date]"


And the "value" (number) of
observation_source=
is what I want to change. For example to
[ObsSource]
so I get a string like this:

String Url = Adress + "?station_ids=1322&observation_source=[ObsSource]&starttime=[date]"


I want to do this so I can
replace
"[ObsSource]" with my own value later to scan different "observation sources"

The observation_source value can be anything between 1 and 100. What I imagine is possible to is to replace from "observation_source" to the next "?" but I don't know where to start.

Is there regex in c#?

Edit: To clarify, the
"?station_ids=1322&observation_source=[ObsSource]&starttime=[date]"
is not my own making. I get these URLs from a JSON object someone else made. I can't make changes to how the string looks from the sender, just what I do with it once i have it.

Answer
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"observation_source=(\d+)");
string url2 = re.Replace(Url, (m) =>
{
  return m.Value.Replace(m.Groups[1].Value, "[ObsSource]");
});
Comments