Matthias
Matthias

Reputation: 53

Extracting information from a string

So I got this string

G-Eazy - The track title (Mr. Awesome Remix) (Official Video)

Now I would like to extract information like the artist, song title, remix and ignore the information about the official video.

That means that I am just assuming that the first part is the artist's name followed by a space and minus sign and a space again. Then I would like to retrieve the content of the first brackets and ignore all brackets containing words like "official" and so on...

Is there any way to do that using regex?

Upvotes: 1

Views: 105

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 241088

The expression /^(.+?)\s+\-\s+(.+?)\s*\((.+?)\)/ seems to work as expected.

Example Here

var string = 'G-Eazy - The track title (Mr. Awesome Remix) (Official Video)';
var matches = string.match(/^(.+?)\s+\-\s+(.+?)\s*\((.+?)\)/);

document.querySelector('pre').textContent =
  'Artist: ' + matches[1] 
+ ' \nTitle: ' + matches[2]
+ '\nRemix: ' + matches[3];
<pre></pre>

Output:

Artist: G-Eazy

Title: The track title

Remix: Mr. Awesome Remix

Upvotes: 2

N. Leavy
N. Leavy

Reputation: 1094

If you are struggling with how to match the - that separates the artist from the track name without matching on the - in the artist name, then the trick is to match on something like ([^ ]| [^-])+ for the artist name. That will match "anything but a space, or a space not followed by a dash" repeatedly. Obviously we'd like to support spaces in the artist name as well.

For the whole expression, something like this should work:

var str = 'G-Eazy - The track title (Mr. Awesome Remix) (Official Video)'
var re = /^((?:[^ ]| [^- ])+) - ([^(]+)(?:\(([^)]+)[Rr]emix\))?/;
var m  = str.match(re); 
console.log('Artist: ' + m[1]);
console.log('Tack  : ' + m[2]);
console.log('Remix : ' + m[3]);

Upvotes: 1

kn0wmad1c
kn0wmad1c

Reputation: 110

Depending on whether all the data coming in is in an expected similar format or not, you could do it using the string tokenizing method .split().

var string = "G-Eazy - The track title (Mr. Awesome Remix) (Official Video)";

var artist = string.split('-')[0];
alert(artist); // "G-Eazy "
var title = string.split('-')[1].split('(Official')[0];
alert(title); // " The track title (Mr. Awesome Remix) ";

artist = artist.trim();
title = title.trim();

alert(artist + " - " + title); // "G-Eazy - The track title (Mr. Awesome Remix)"

Upvotes: 0

Related Questions