2014-03-19 74 views
0

我有一個像正則表達式一切

[{"id":"9","label":"P","price":"0","oldPrice":"0","products":["606","610","614","618","622","625","629"]},{"id":"8","label":"M","price":"0","oldPrice":"0","products":["607","611","615","619","626","630"]},{"id":"7","label":"G","price":"0","oldPrice":"0","products":["609","613","617","621","624","628","632"]},{"id":"36","label":"GG","price":"0","oldPrice":"0","products":["608","612","616","620","623","627","631"]},{"id":"152","label":"XGG","price":"0","oldPrice":"0","products":["3713","6577","6578","6579","6580","6581","6582"]}] 

我需要一個String是標籤值:P,M,G,GG,XGG。我試圖讓標籤和逗號之間的一切,但它不工作

「(標籤)(。*)(,)」

+5

'JSON'解析器...? – Reimeus

回答

3
(?<=label\"\:)\"\w+\" 

這將做到這

或者,如果你真的想它解析爲JSON

做到這一點

var arr = []; 
var jso = [{"id":"9","label":"P","price":"0","oldPrice":"0","products":["606","610","614","618","622","625","629"]},{"id":"8","label":"M","price":"0","oldPrice":"0","products":["607","611","615","619","626","630"]},{"id":"7","label":"G","price":"0","oldPrice":"0","products":["609","613","617","621","624","628","632"]},{"id":"36","label":"GG","price":"0","oldPrice":"0","products":["608","612","616","620","623","627","631"]},{"id":"152","label":"XGG","price":"0","oldPrice":"0","products":["3713","6577","6578","6579","6580","6581","6582"]}]; 
console.log(jso.length); 
for(var i=0;i<jso.length;i++){ 
    arr.push(jso[i].label); 
} 
console.log(arr); 

正則表達式演示:http://regex101.com/r/kT9kE6

5

此字符串是JSON格式,因此建議使用JSON解析器,而不是http://www.json.org/使用正則表達式

閱讀關於JSON格式。

此鏈接提供解釋了有關JSON在Java http://www.json.org/java/

+0

謝謝你,我知道它在JSON中,但我不能使用解析器,它來自一個我無法改變的網絡爬蟲的String對象。 –

+0

您可以解析字符串中存在的JSON內容 – anirudh

0

你的正則表達式是貪婪的。

將其更改爲懶惰

label.*?,

您也可以使用條件正則表達式來只獲取標籤中使用的條件表達式

正則表達式的值

(?<="label":")\w+

Regex Demo

0

你或許應該使用JSON解析器,但是......

此正則表達式將捕獲的組名的所有標籤「標籤」

.*?(?:label)":"(?<labels>[^"]+)+.*? 

或取決於你如何執行此操作,只需搜索這場比賽

(?:label)":"(?<labels>[^"]+) 

你可以看到它在這裏工作:http://regex101.com/r/fS8jA8

由此產生的JAVA(由regex101生成):

String re = "(?:label)\\":\\"(?<labels>[^\\"]+)"; 
String str = "[{\"id\":\"9\",\"label\":\"P\",\"price\":\"0\",\"oldPrice\":\"0\",\"products\":[\"606\",\"610\",\"614\",\"618\",\"622\",\"625\",\"629\"]},{\"id\":\"8\",\"label\":\"M\",\"price\":\"0\",\"oldPrice\":\"0\",\"products\":[\"607\",\"611\",\"615\",\"619\",\"626\",\"630\"]},{\"id\":\"7\",\"label\":\"G\",\"price\":\"0\",\"oldPrice\":\"0\",\"products\":[\"609\",\"613\",\"617\",\"621\",\"624\",\"628\",\"632\"]},{\"id\":\"36\",\"label\":\"GG\",\"price\":\"0\",\"oldPrice\":\"0\",\"products\":[\"608\",\"612\",\"616\",\"620\",\"623\",\"627\",\"631\"]},{\"id\":\"152\",\"label\":\"XGG\",\"price\":\"0\",\"oldPrice\":\"0\",\"products\":[\"3713\",\"6577\",\"6578\",\"6579\",\"6580\",\"6581\",\"6582\"]}] 
"; 

Pattern p = Pattern.compile(re, Pattern.CASE_INSENSITIVE); 
Matcher m = p.matcher(str);