Home > OS >  Finding the `/` character as a separator using regexp as for phrases wrapped and not wrapped by othe
Finding the `/` character as a separator using regexp as for phrases wrapped and not wrapped by othe

Time:04-14

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

  • / is a separator between each string, e.g: /string1/string2/string3/
  • The / is also a separator between regular expressions like /regexp1//regexp2//regexp3/

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
/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

CodePudding user response:

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
  • Related