2016-04-25 22 views
8

Sto faticando a dividere la seguente stringa in due parti. Principalmente perché uno dei possibili delimitatori è un carattere spazio, che può apparire nel secondo gruppo di cattura.Stringa divisa al primo evento

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

Come posso dividere queste stringhe alle due \s, \skeyword\s o \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"] 
+1

Si desidera utilizzare un unico regex per abbinare tutti i casi precedenti? – Ismail

+0

Che ne dici di fare un passo indietro e rimuovere tutte le istanze di 'keyword' e' key', quindi usare Regex? –

+0

Cosa c'è di sbagliato nella regex che hai? Si noti che questo strumento sta utilizzando un test STRING singolare e, pertanto, si presuppone che tutto nell'input sia una stringa lunga, quando si intende che siano stringhe multiple individuali. – Hamms

risposta

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

funzionerà per tutti i casi hai dato.
Demo here.

+0

Ben fatto, +1 !! –

+0

Questo è sorprendente. Grazie James! Sfortunatamente il caso 'stringa stringa' deve includere caratteri alfanumerici e non solo caratteri di parole. Come posso aggiungere questo? :) '(\ skeyword \ s | \ skey \ s | \ s (? =. * [\ [{] | [a-z0-9 -] + $))'? – ThomasReggi

+0

@ThomasReggi Vedi la mia risposta aggiornata, dovrebbe fare il trucco. –

3

È possibile sostituire "keyword" e "key" con stringa vuota "", poi diviso \s+

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

@ThomasReggi In alternativa è possibile sostituire 'keyword | key' con carattere virgola', 'quindi chiama' .split (/, /) ' – guest271314

Problemi correlati