多次使用两个字符串之间的正则表达式

时间:2014-03-19 13:41:50

标签: java regex string matcher

我有一个类似

的字符串
[{"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"]}]

我需要的是标签值:P,M,G,GG,XGG。我试图在标签和逗号之间获取所有内容,但它不起作用

  

"(标签)(,)&#34(*);

4 个答案:

答案 0 :(得分:5)

此字符串采用JSON格式,因此建议使用JSON解析器而不是使用正则表达式

http://www.json.org/中了解JSON格式。

此链接提供了有关Java http://www.json.org/java/

中JSON的说明

答案 1 :(得分: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

答案 2 :(得分:0)

你的正则表达式很贪婪。

将其更改为lazy

label.*?,

您还可以使用条件正则表达式来仅获取标签值

正则表达式使用条件表达式

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

Regex Demo

答案 3 :(得分: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);