Use regexp in presto to remove the last slash only when it's preceded by a character

Viewed 1431

Is there a way in Presto or SQL to remove the last backslash only when it is preceded by a character and keep it otherwise?

I am using regexp_replace in presto. So for example if x = '/' The expression should return '/' and if x = 'beta/alpha/' it should return 'beta/alpha'

I am using select regexp_replace ([expression], '[\/]$', '').

This returns an empty string when there is only a backslash and removes the backslash from the end of the string if the expression has some characters before the backslash.

1 Answers

You can use

regexp_replace([expression], '([^/])/$', '$1')
-- or
regexp_replace([expression], '(?<=[^/])/$', '')

See the regex demo.

Details

  • ([^/])/$ - matches and captures any char but / into Group 1 (with the ([^/]) pattern, the $1 in the replacement pattern is a replacement backreference that refers to the Group 1 value), then matches a / at the end of string ($)
  • (?<=[^/])/$ matches a / at the end of a string only when the char immediately on the left is not a / char (and not the start of a string).
Related