鍍金池/ 問答/Java/ Java正則匹配數(shù)字串

Java正則匹配數(shù)字串

我要提取

SyncKey =  {"Count": 4,"List": [{"Key": 1,"Val": 694398478},{"Key": 2,"Val": 694398818},{"Key": 3,"Val": 694398792},{"Key": 1000,"Val": 1525475042}]}

四個val后面的數(shù)字,請問正則表達(dá)式要怎么寫

回答
編輯回答
憶當(dāng)年

json數(shù)據(jù)都有非常多非常好的解析工具,如果是javascript,甚至都是內(nèi)置的,不建議用正則,
原因:

1. 正則易寫不易維護(hù);
2. 總有你測試不到的特殊情況;
3. 不通用,如果你想得到更多字段的數(shù)據(jù), 正則不適合做這件事.

不過,既然一定要,可以試試這個:

js:

    SyncKey = {"Count": 4,"List": [{"Key": 1,"Val": 694398478},{"Key": 2,"Val": 694398818},{"Key": 3,"Val": 694398792},{"Key": 1000,"Val": 1525475042}]}
    res = JSON.stringify(SyncKey)
    var myregexp = /"Val":(\d+)/g;
    var match = myregexp.exec(res);
    while (match != null) {
        // matched text: match[0]
        // match start: match.index
        // capturing group n: match[n]
        console.log(match[1])
        match = myregexp.exec(res);
    } 

Java:

    import java.util.regex.*;
    
    
     public class RegTest{
     
        public static void main(String[]  args){
            String SyncKey = "{\"Count\": 4,\"List\": [{\"Key\": 1,\"Val\": 694398478},{\"Key\": 2,\"Val\": 694398818},{\"Key\": 3,\"Val\": 694398792},{\"Key\": 1000,\"Val\": 1525475042}]}";
            
            Pattern p = Pattern.compile("\"Val\":\\s*(\\d+)");
            Matcher m = p.matcher(SyncKey);
            
            while (m.find()) {
                System.out.println(m.group(1));                    
            }        
            
        }
    
    }
2018年4月6日 17:10