falek.marcin
falek.marcin

Reputation: 10659

Finding the `/` character as a separator using regexp as for phrases wrapped and not wrapped by other `/` characters

I'm trying to create a regexp that can find occurrences of / from a string however the following rules must be satisfied:

The goal is to find all occurrences of the separator / that satisfy such a condition enter image description here

As a result, I would like to get the separators between the following phrases

/string1/string2/string3//regexp1///regexp2///regexp3//string4/

Currently I prepared the following regexp, but unfortunately it doesn't work as I expect, because it doesn't handle when there are 2 regexps next to each other. Does anyone have any advice how to overcome such case?

((?<=\/)\/(?=\/)|(?<!\/)\/(?!\/)|(?<=\w)\/(?=\/)|(?<=\/)\/(?=\w)|\/$)

enter image description here

Upvotes: 1

Views: 355

Answers (1)

anubhava
anubhava

Reputation: 786081

You may use this regex with an alternation and grab capture group #1:

(?<=\/)(\/[^\/]+\/|[^\/]+)(?:\/|$)

RegEx Demo

RegEx Details:

  • (?<=\/): Assert that previous character is /
  • ( Start capture group #1
    • \/: Match a /
    • [^/]+: Match 1+ non-/` characters
    • \/: Match a /
    • |: OR
    • [^\/]+: Match 1+ non-/ characters
  • ): End capture group #1
  • (?:\/|$): Match a / or end position

Upvotes: 1

Related Questions