简体   繁体   中英

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"]
(\skeyword\s|\skey\s|\s(?=.*[\[{]|[^\]}]+$))

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

您可以将"keyword""key"替换为空字符串"" ,然后拆分\\s+

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM