2

I need to regex every match of a string (including empty string!) separated by slash but the regex returns also empty string after each occurrence.

Examples (always 4 matches):

root/level1/level2/level3
/level1//level3
root/level1/level2/

Pattern:

  • [^\/]* - return 8 matches (empty string after and before ) instead of 4

I also tried to use IF-THEN-ELSE clause but it did not help :-(

My regex playground

I've searched dozens of articles but did not find any solution.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Michal
  • 55
  • 4

1 Answers1

1

You may use

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

See the regex demo and the regex graph:

enter image description here

Details

  • [^\/]+ - 1+ chars other than /
  • | - or
  • (?<=\/|^)(?=\/|$) - a location that is immediately preceded with / or start of string and immediately followed with / or end of string.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397