Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 644
ThomasReggi Avatar asked Apr 25 '16 23:04

ThomasReggi


2 Answers

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

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

like image 173
James Buck Avatar answered Nov 18 '22 01:11

James Buck


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

str.replace(/keyword|key/g, "").split(/\s+/)
like image 43
guest271314 Avatar answered Nov 18 '22 03:11

guest271314