Search code examples
regexnegative-lookbehind

Regex match character with negative lookbehind of two chars


I want to split a string using the character "/", but the split should only occur if there is no "\" in front of it.

String:

/10/102-\/ABC083.013/11/201201/20/83/30/463098194/32/7.7/40/0:20

Regex:

\/*(?<!\\)[^\/]*\/*(?<!\\)[^\/]*

Expected result:

/10/102-\/ABC083.013
/11/201201
/20/83
/30/463098194
/32/7.7
/40/0:20

But with my regex I get:

/10/102-\
/ABC083.013/11
/201201/20
/83/30
/463098194/32
/7.7/40
/0:20

online regex example

The issue is on the first group "/10/102-\/ABC083.013", it does not recognize the string "\/" to the first group. I don't know how to optimize/change my regex so that it recognizes the first group correctly.


Solution

  • You can use

    (?:\/[^\\\/]+){2}(?:\\\/[^\\\/]+)?
    

    See the regex demo. Details:

    • (?:\/[^\\\/]+){2} - two occurrences of
      • \/ - a / char
      • [^\\\/]+ - one or more chars other than / and \
    • (?:\\\/[^\\\/]+)? - an optional occurrence of:
      • \\ - a \ char
      • \/ - a / char
      • [^\\\/]+ - one or more chars other than / and \