regex - split word by special character -


i want find pairs of words separated ":" let me explain examples:

aa:bbb  

(output) match1=> aa; bbb

aa: bbb ccc  

(output) match1=> aa; bbb ccc

aaa: bbbbb ccc ddd: eeee 

(output)match1=> aaa; bbbb ccc (output)match2=> ddd; eee


i found 2 regex:

1)\s*([a-z0-9]+)+\s*\:\s*([a-z0-9]+)+

2)(.*)\:(.+?)(?=[a-z0-9]*\s*:)

the first found occurance not work in case example(word separated white space bbbbb ccc):

aaa: bbbbb ccc 

but work in case:

aa: bbb ccc:dd eeee:fff 

the second not found occurance work in case:

aaa: bbbbb ccc 

to answer regex despite may not best way it:

(\w+ *):([\w ]+)(?!\w* *:)

demo here

i make 2 capture groups, 1 before :, 1 after.

to sure second capture group doesn't take "key" of next 1 use negative lookahead ensure can't match format of key after (any word or space character before :)

to match keys use \w+ * @ lest 1 char followed or not 1 or more space , negative lookahead \w* *: sure can't match single :, nor a: or a :

for values use character class, word character (\w a-za-z0-9_) or space @ least once.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -