archerarjun
archerarjun

Reputation: 23

regex - Replace multiple occurrences

I have a string, Can be any of the below cases:

  1. test1/test2/test3/test4/test5/
  2. test1/test2/test3/test4//
  3. test1/test2/test3///
  4. test1/test2////
  5. test1/////

My expected results are

  1. test1/test2/test3/test4/test5
  2. test1/test2/test3/test4

  3. test1/test2/test3

  4. test1/test2
  5. test1 How can i achieve using regex ?

Currently, i am using regexp_replace(col, "/+/", "/") it is working but leaving an extra / on the end.

Upvotes: 1

Views: 1225

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

regexp_replace(col, '/+$|(/){2,}', '\\1')

See the regex demo.

Details

  • /+$ - 1 or more / at the end of the string
  • | - or
  • (/){2,} - two or more slashes, the last of which will be saved in Capturing group 1 that you will be able to refer to from the replacement pattern using the \1 placeholder.

Upvotes: 2

Poul Bak
Poul Bak

Reputation: 10929

You can use the following regex:

/\/+$/gm

and replace with an empty string ('').

The regex will match one or more slashes in the end of the string, then will replace those with the empty string, meaning the paths will no longer end in a slash.

Upvotes: 0

Related Questions