zaynetro
zaynetro

Reputation: 2308

Regular expression improvement

I am trying to write regular expression to capture data, but struggling to finish it.

From the data:

Code:Name Another-code:Another name

I need to get an array:

['Code:Name', 'Another-code:Another name']

The problem is that Codes can be almost anything but space.

I know how to do it without using regular expressions, but decided to give them a chance.

UPDATE: Forgot to mention that number of elements can vary from one to infinity. So the data:

Code:Name -> ['Code:Name']
Code:Name Code:Name Code:Name -> ['Code:Name', 'Code:Name', 'Code:Name']

is also suitable.

Upvotes: 0

Views: 37

Answers (3)

anubhava
anubhava

Reputation: 784998

Here is a way to do this without using regex:

var s = 'Code:Name Another-code:Another name';

if ((pos = s.indexOf(' '))>0) 
   console.log('[' + s.substr(0, pos) + '], [' + s.substr(pos+1) + ']');

//=> [Code:Name], [Another-code:Another name] 

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Just split the input according to the space which is followed by one or more non-space characters and a : symbol.

> "Code:Name Another-code:Another name".split(/\s(?=\S+?:)/)
[ 'Code:Name', 'Another-code:Another name' ]

OR

> "Code:Name Another-code:Another name".split(/\s(?=[^\s:]+:)/)
[ 'Code:Name', 'Another-code:Another name' ]

Upvotes: 2

Toto
Toto

Reputation: 91385

How about:

^(\S+:.+?)\s(\S+:.+)$

Code:Name is in group 1 and Another-code:Another name in group 2.

\S+ means one or more character that is not a space.

Upvotes: 1

Related Questions