Your current attempt is good, but the match is greedy. It looks for the longest possible match, not the shortest. Adding a
? after the
.+ would work fine. To understand "greedyness," check the perldocs for regular expressions:
perlre
m{/(.*?)/}
A second issue is if the string has empty slots between slashes, such as the string "%///US1252691001". You probably want to be able to return an empty result in this case, so I changed your use of .+ (one or more) to .* (zero or more) characters. Otherwise, you might get a match back of "/" for strings like my example.
Update: As others mentioned but I didn't parse correctly, to get the THIRD field (e.g., "~/~/THIS/~") takes a little more work. Instead of a bunch of complicated lookaheads and lookbehinds, or switching to a split() instead, I would just parse through. This has the advantage of easily changing the pattern to capture the other fields if the requirements change.
m{/.*?/(.*?)/}
--
[ e d @ h a l l e y . c c ]