ThomasReggi
ThomasReggi

Reputation: 59355

Split string at first occurrence

I'm struggling splitting the following string into two pieces. Mainly because the one of the possible delimiters is a space character, which can appear in the second capture group.

https://regex101.com/r/dS0bD8/1

How can I split these strings at either \s, \skeyword\s, or \skey\s?

'[] []' // => ['[]', '[]']
'[] keyword []' // => ['[]', '[]']
'[] key []' // => ['[]', '[]']

'[] ["can contain spaces"]'  // => ['[]', '["can contain spaces"]']
'[] keyword ["can contain spaces"]' // => ['[]', '["can contain spaces"]']
'[] key ["can contain spaces"]' // => ['[]', '["can contain spaces"]']

'{} {}' // => ['{}', '{}']
'{} keyword {}' // => ['{}', '{}']
'{} key {}' // => ['{}', '{}']

'{} {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']
'{} keyword {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']
'{} key {"can":"contain spaces"}' // => ['{}', '{"can":"contain spaces"}']

'string string' // => ["string", "string"]
'string keyword string' // => ["string", "string"]
'string key string' // => ["string", "string"]

Upvotes: 8

Views: 1023

Answers (2)

guest271314
guest271314

Reputation: 1

You can replace "keyword" and "key" with empty string "", then split \s+

str.replace(/keyword|key/g, "").split(/\s+/)

Upvotes: 3

James Buck
James Buck

Reputation: 1640

(\skeyword\s|\skey\s|\s(?=.*[\[{]|[^\]}]+$))

Will work for all the cases you gave.
Demo here.

Upvotes: 8

Related Questions