Search code examples
javaregexmagnolia

java regex add trailing slash


I am trying to redirect the urls to add trailing slash

/news -> /news/
/news?param1=value1 -> /news/?param1=value
/news#anchor?param1=value1 -> /news/#anchor?param1=value1

I need to do it through a regex that identifies only the path and add /. When there are no parameters there is no problem.

^(/[a-z0–9/_\-]*[^/])$ -> $1/

But when there are parameters I am not able to create the regular expression that separates the path from the parameters.

Any ideas?, thanks


Solution

  • Might be just need to extend the end of string past the parameters.
    To cover both with and without parameters might be:

    ^(/[a-z0–9/_-]*(?<!/))([^/]*)$ -> $1/$2

    see https://regex101.com/r/Iwl23o/2