user762579
user762579

Reputation:

get substrings from a delimited string excepted the last one

having strings like

booboo-en
booboo-duck-en
booboo-the-duck-en
booboo-the-duck-so-nice-en

I tried to extract all the strings (whatever number of delimited groups) except the last one (-en) to get :

booboo
booboo-duck
booboo-the-duck

and so on...

Using

^((?:[^-]+-){2}[^-]+).*$

I can extract 2 groups , but I don't see how to modify it for any number of groups ...

Upvotes: 1

Views: 221

Answers (2)

user78110
user78110

Reputation:

why are you using regex for this?

at least any scripting language has a split primitive

they usually return arrays

combining split and removing the last element of an array is trivial

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Try this:

^.*(?=-[^-]*$)

This will match the string up until just before the final dash:

^       # Start of string
.*      # Match any number of characters
(?=     # until it's possible to match:
 -      #  a dash
 [^-]*  #  followed only by characters other than dashes
 $      #  until the end of the string.
)       # (End of lookahead assertion)

Upvotes: 0

Related Questions