[英]Extracting information from a string
所以我得到了這個字符串
G-Eazy - The track title (Mr. Awesome Remix) (Official Video)
現在我想提取藝術家,歌曲名稱,混音等信息,並忽略有關官方視頻的信息。
這意味着我只是假設第一部分是藝術家的名字,后面是空格,減號和空格。 然后我想檢索第一個括號的內容,並忽略包含像“官方”等詞語的所有括號......
有沒有辦法使用正則表達式?
表達式/^(.+?)\\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>
輸出:
藝術家:G-Eazy
標題:曲目標題
混音:Awesome Remix先生
如果你正在努力如何匹配-
將藝術家與曲目名稱分開而不匹配-
在藝術家名稱中,那么訣竅是匹配像([^ ]| [^-])+
的東西藝術家姓名。 這將反復匹配“除了空間之外的任何東西,或者沒有后跟破折號的空間”。 顯然我們也想支持藝術家名字中的空格。
對於整個表達式,這樣的東西應該工作:
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]);
根據所有數據是否都是預期的類似格式,您可以使用字符串標記方法.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)"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.