从string中提取信息

所以我得到了这个string

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

现在我想提取艺术家,歌曲标题,混音等信息,并忽略有关官方video的信息。

这意味着我只是假设第一部分是艺术家的名字,再次是空格,减号和空格。 然后,我想检索第一个括号的内容,并忽略所有包含“官方”等字样的括号…

有没有办法做到这一点使用正则expression式?

expression/^(.+?)\s+\-\s+(.+?)\s*\((.+?)\)/似乎按预期工作。

示例在这里

 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> 

如果你正在努力如何匹配-艺术家与曲目名称没有匹配-在艺术家名称中匹配-然后技巧是匹配的东西像([^ ]| [^-])+为艺术家名字。 这将匹配“任何东西,而不是一个空间,或一个没有跟着破折号”的空间。 显然我们也想支持艺术家名字中的空格。

对于整个expression,这样的事情应该工作:

 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]); 

根据所有进入的数据是否采用预期的相似格式,可以使用string标记方法.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)"