Chris L
Chris L

Reputation: 103

Is there a way to replace string in URL that precedes a known string?

I am trying to find a way to replace an arbitrary number in an URL that is followed by a known element.

For example, finding "20200116141908/smaller_square" in the original where "/smaller-square" is always following the arbitrary number is arbitrary, and replace both with "/large", for the result below:

ORIGINAL:

https://www.artforhire.com/p/assets/images/images/023/441/726/20200116141908/smaller_square/bear.jpg
                                                             ^------------REPLACE---------^

Intended result:

https://www.artforhire.com/p/assets/images/images/023/441/726/large/bear.jpg

Upvotes: 1

Views: 46

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

Using Regex:

string newUrl = Regex.Replace(originalUrl, @"\d+\/smaller_square", "large");

\d+ matches one or more digits.

If there are always 14 digits then you can use \d{14} instead.

Upvotes: 3

Related Questions