Regex 从除最后一个字符串外的分隔字符串中获取子字符串

Regex 从除最后一个字符串外的分隔字符串中获取子字符串,regex,Regex,有像 booboo-en booboo-duck-en booboo-the-duck-en booboo-the-duck-so-nice-en 我试图提取除最后一个(-en)之外的所有字符串(无论分隔组的数量如何),以获得: 等等 使用 我可以提取2个组,但我看不出如何对任意数量的组进行修改…尝试以下方法: ^.*(?=-[^-]*$) 这将匹配字符串,直到最后一个破折号之前: ^ # Start of string .* # Match any number of

有像

booboo-en
booboo-duck-en
booboo-the-duck-en
booboo-the-duck-so-nice-en
我试图提取除最后一个(
-en
)之外的所有字符串(无论分隔组的数量如何),以获得:

等等

使用

我可以提取2个组,但我看不出如何对任意数量的组进行修改…

尝试以下方法:

^.*(?=-[^-]*$)
这将匹配字符串,直到最后一个破折号之前:

^       # 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)

你为什么要用正则表达式呢

至少任何脚本语言都有拆分原语

它们通常返回数组


组合拆分和删除数组的最后一个元素很简单

不可能创建具有可变捕获数的正则表达式(perl中可能除外)。您使用的是哪种语言或工具?您也可以使用lastIndexOf和substring实用程序来完成此操作…每个字符串末尾是否固定了
-en
?-en不固定,但我意识到它总是相同的长度(3),所以我可能会基于string.length-3进行子字符串提取…我的原始代码使用正则表达式,但确实有很多其他方法可以做到这一点
^.*(?=-[^-]*$)
^       # 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)