使用Regex作为分隔符来分割字符串

时间:2011-04-12 05:26:15

标签: ruby regex split

我想将以下字符串拆分为两个子字符串。 “somestring(otherstring)”

我带来了以下正则表达式分裂

"somestring(otherstring)".split(/(.+)\((.+)\)/)

但是这会排除以下字符串,这些字符串在大括号中没有子字符串。 “somestring”

如何更改正则表达式,以便即使没有模式“(otherstring)”的子字符串,它仍然会生成第一个子字符串作为输出。

提前多多感谢!

2 个答案:

答案 0 :(得分:8)

>> "somestring(otherstring)".split(/[()]/)
=> ["somestring", "otherstring"]
>> "somestring".split(/[()]/)
=> ["somestring"]

答案 1 :(得分:1)

尝试使用类似这样的正则表达式:/([^\(\)]+)(?:\((.+)\))?/

相关问题