2016-09-21 125 views
-1

我想解析一個itunes XML庫。我想從XML文件中獲取所有獨特藝術家名稱的數組。我已經嘗試將它轉換爲JSON,但itunes將它們的庫存儲在XML中的方式使得訪問庫中的所有藝術家名稱變得非常困難。正則表達式對此目的更有效。使用Javascript的正則表達式只返回兩個字符串之間的字符串

文件的格式是這樣的:

<dict> 
 
    <key>Track ID</key><integer>219</integer> 
 
    <key>Name</key><string>Something Sweet, Something Tender</string> 
 
    <key>Artist</key><string>Eric Dolphy</string> 
 
    <key>Album Artist</key><string>Eric Dolphy</string> 
 
    <key>Album</key><string>Out to Lunch (Remastered)</string> 
 
    <key>Genre</key><string>Jazz</string> 
 
    <key>Kind</key><string>Purchased AAC audio file</string> 
 
    <key>Size</key><integer>12175953</integer> 
 
    <key>Total Time</key><integer>363949</integer> 
 
    <key>Disc Number</key><integer>1</integer> 
 
    <key>Disc Count</key><integer>1</integer> 
 
    <key>Track Number</key><integer>2</integer> 
 
    <key>Track Count</key><integer>5</integer> 
 
    <key>Year</key><integer>1964</integer> 
 
    <key>Date Modified</key><date>2016-04-29T09:36:10Z</date> 
 
    <key>Date Added</key><date>2007-08-04T16:57:47Z</date> 
 
    <key>Bit Rate</key><integer>256</integer> 
 
    <key>Sample Rate</key><integer>44100</integer> 
 
    <key>Release Date</key><date>1964-02-25T00:00:00Z</date> 
 
    <key>Artwork Count</key><integer>1</integer> 
 
    <key>Sort Album</key><string>Out to Lunch</string> 
 
    <key>Sort Artist</key><string>Eric Dolphy</string> 
 
    <key>Sort Name</key><string>Something Sweet, Something Tender</string> 
 
    <key>Persistent ID</key><string>4AE13A27A2113C97</string> 
 
    <key>Track Type</key><string>Remote</string> 
 
    <key>Purchased</key><true/> 
 
</dict>

我有一個XML文件,該文件可能包含數百個不同的藝術家。 「數據」是上述XML示例只是一個軌道的xml文件的內容。

我正在使用正則表達式和string.match()匹配: <key>Artist</key><string>Eric Dolphy</string> 並返回藝術家的名字。它返回所有匹配的數組,但我只想要藝術家名稱而不是xml標籤。我發現在javascript中使用string.match()和regex/g會返回一個包含所有匹配的子字符串的數組,但不會返回捕獲組。 有沒有一種方法在JavaScript中,我可以得到一個數組返回只是藝術家名稱而無需使用str.replace()來替換我不想用空字符串之後的所有內容?

let artists = data.toString().match(/<key>Artist<\/key><string>(.*?)<\/string>/g); 
 
let uniqueArtists = Array.from(new Set(artists))

+0

使用前瞻和回顧後。 – Barmar

+1

什麼是數據?你是如何創建這個對象的? – trincot

+1

永遠不要使用正則表達式解析XML。 – Bergi

回答

-1

匹配返回您正則表達式的匹配來的數組。數組中的第一項將是完整匹配,第二項將匹配您的第一個子模式(在圓括號之間)。等等。

你要尋找的是:

let artist = artists[1];

相關問題