Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Maisen1886 Avatar asked Nov 20 '25 23:11

Maisen1886


1 Answers

Another option is to match 2 times a forward slash, and only match a / when preceded by a \

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

Explanation

  • (?: Non capture group
    • \/ Match /
    • (?: Non capture group
      • [^\/] Match any char other than /
      • | Or
      • (?<=\\)\/ Match / not preceded by \
    • )+ Close group and repeat 1+ times to match at least 1 char other than /
  • ){2} Close group and repeat 2 times

Regex demo


Or a slightly more efficient unrolled version

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

Explanation

  • (?: Non capture group
    • \/[^\\\/]+ Match / followed by 1+ times any char other than \ and /
    • (?: Non capture group
      • \\.[^\\\/]* Match an escaped char followed by 0+ times any char other than \ and /
    • )* Close the group and repeat 0+ times (in case there are no occurrences of an escaped char)
  • ){2} Close group and repeat 2 times

Regex demo

like image 140
The fourth bird Avatar answered Nov 24 '25 22:11

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!