Home > Back-end >  Regex Replace that works with and without trailing slash
Regex Replace that works with and without trailing slash

Time:06-08

I am trying to match a url string and I want to swap when some word is included in this case reviews the problem is that when the url ends on a forward slash my formula adds a double slash. Is there a way to add a slash only when there is no slash at the end?

https://regex101.com/r/cjMEiW/1

CodePudding user response:

Is there a way to add a slash only when there is no slash at the end?

The 'trick' is to use an additional 'dummy' (not used in substitution) group (\/?) which can be empty or contain a slash and not to allow the group 3 to include a slash at its end (.*[^\/$])

See: https://regex101.com/r/nysBYY/2

Regex:

(<a href='https:\/\/www\.example\.com)\/(reviews)\/(.*[^\/$])(\/?)('>)

Test string:

<a href='https://www.example.com/reviews/citroen/c4/'>here</a>
<a href='https://www.example.com/reviews/citroen/c4'>here</a>

Substitution:

$1/$3/$2/$5

Output:

<a href='https://www.example.com/citroen/c4/reviews/'>here</a>
<a href='https://www.example.com/citroen/c4/reviews/'>here</a>

Check out the answer https://stackoverflow.com/a/72516646/7711283 at Regex, substitute part of a string always at the end for more detailed explanation of the regex of the groups.


P.S. the OPs regex was:


(<a href='https:\/\/www\.example\.com)\/(reviews)\/(.*)('>)

with substitution $1/$3/$2/$4 which resulted in:

<a href='https://www.example.com/citroen/c4//reviews/'>here</a>
<a href='https://www.example.com/citroen/c4/reviews/'>here</a>
  • Related