java正则表达式处理一段字符串得到指定字符后面的字符,

"{hello:{"名字":"李四"}}",通过名字:获取李四

第1个回答  2013-09-04
var b=""{hello:{"名字":"李四"}}""
var reg=new RegExp("李四","gi");
var a=ret.exec(b);
第2个回答  推荐于2017-12-16

为什么要用正则呢。java里边可以用工具类去解析得到呀。 

有现成的。

像org.json包等。


用正则的话也可以。

package test;  
  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
public class Test {  
    public static void main(String[] args) {  
        String s = "[{\"name\":\"zhangsan\",\"sex\":\"男\"},{\"name\":\"lisi\",\"sex\":\"女\"},{\"name\":\"wangwu\",\"sex\":\"男\"}]";  
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
        Map<String, String> map = null;  
        Pattern p = Pattern.compile("(\"\\w+\"):(\"[^\"]+\")");  
        Matcher m = p.matcher(s);  
        String[] strs = null;  
        while (m.find()) {  
            strs = m.group().split(":");  
            if (strs.length == 2) {  
                map = new HashMap<String, String>();  
//              System.out.println(_strs[0].replaceAll("\"", "").trim() + "="  
//                      + _strs[1].trim().replaceAll("\"", ""));  
                map.put(strs[0].replaceAll("\"", "").trim(), strs[1].trim()  
                        .replaceAll("\"", ""));  
                list.add(map);  
            }  
  
        }  
         System.out.println(list);  
    }  
}

本回答被提问者采纳
相似回答