0

How can I get from this string

genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990

this

genre: [Drama, Comedy],
cast: [Leonardo DiCaprio, Cmelo Hotentot],
year: [1986-1990]

with one regular expression?

3
  • 5
    Why does it have to be just one regex? Commented Apr 10, 2012 at 16:13
  • 1
    you can't, in general, because there are two levels of grouping for teh results (subject and entry), and regexps only support a single level. Commented Apr 10, 2012 at 16:15
  • I hoped for an elegant one regex :) I was just curious if it could be done Commented Apr 10, 2012 at 16:16

3 Answers 3

1

This could be done using one regex and overload of replace function with replacer as a second argument. But honestly, I have to use one more replace to get rid of pluses (+) - I replaced them by a space () char:

var str = 'genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990';
str = str.replace(/\+/g, ' ');
var result = str.replace(/(\w+:)(\s?)([\w,\s-]+?)(\s?)(?=\w+:|$)/g, function (m, m1, m2, m3, m4, o) {
    return m1 + ' [' + m3.split(',').join(', ') + ']' + (o + m.length != str.length ? ',' : '') + '\n';
});

You could find the full example on jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

1

You will not get them into arrays from the start, but it can be parsed if the order stays the same all the time.

var str = "genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990";
str = str.replace(/\+/g," ");

//Get first groupings
var re = /genre:\s?(.+)\scast:\s?(.+)\syear:\s(.+)/
var parts = str.match(re)

//split to get them into an array
var genre = parts[1].split(",");
var cast = parts[2].split(",");
var years = parts[3];

console.log(genre);

2 Comments

Unfortunately the order will not stay the same all the time. Actually it will be always different
Than you need to do it in parts!
0

You can't do this using only regular expressions cause you're trying to parse a (tiny) grammar.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.