ThomasReggi
ThomasReggi

Reputation: 59345

Optional ending capture group

I'm trying to have three total capture groups where the last is optional. I'm running into an issue where I'm not sure how to exclude the last delimiter from the last group and also have it look up to the end.

Here's my pattern

/(.+)\@(.+)\:(.+)/

Here's my example strings

test@hello // => ['test', 'hello']
test@hello:optional // => ['test', 'hello', 'optional']

Upvotes: 0

Views: 46

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

Use string.split

string.split(/[:@]/)

[:@] matches a colon or @ symbol then the split function splits the string according to the matched chars.

var s = 'test@hello:optiona'
alert(s.split(/[@:]/))

or

var s = 'test@hello:optiona'
alert(s.match(/[^@:]+/g))

Upvotes: 2

Related Questions