Harsha Lingampally
Harsha Lingampally

Reputation: 140

Using Regex as delimeter to split a string

I want to split the following strings into two substrings. "somestring(otherstring)"

I came with the following regex split

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

but this excludes the following strings, which dont have the substring in braces.. "somestring"

how can change the regex so that, even if there is not substring of the pattern "(otherstring)", it still generates the first substring as output.

thanks a lot in advance!

Upvotes: 2

Views: 3892

Answers (2)

kurumi
kurumi

Reputation: 25599

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

Upvotes: 8

Andy
Andy

Reputation: 778

Try using something like this as the regex: /([^\(\)]+)(?:\((.+)\))?/.

Upvotes: 1

Related Questions