美文网首页
正则表达式同时按Key获取JSON和XML中的多个值

正则表达式同时按Key获取JSON和XML中的多个值

作者: 刘大坝 | 来源:发表于2024-10-10 16:13 被阅读0次
RegTest.java
package com.local;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Calebit
 * @date 2020-08-07 17:01
 */
public class RegTest {

    public static void main(String[] args) {
        String json = "{\"key1\":\"value111\", \"key2\":\"value222\"}";
        String xml = "<root><key1>value11</key1><key2>value22</key2><key3>value33</key3><key4>value44</key4></root>";

        // 正则表达式 
        String regex = "(?:(?:\"(key1|key2)\"\\s*:\\s*\"(.*?)\")|(?:<(key1|key2)>(.*?)</(key1|key2)>))";

        Pattern pattern = Pattern.compile(regex);
        //Matcher matcherJson = pattern.matcher(json);
        Matcher matcherJson = pattern.matcher(xml);

        System.out.println("获取的值:");
        while (matcherJson.find()) {
            //JSON
            String matcheKey = matcherJson.group(1);
            String matcheVal = matcherJson.group(2);
            if (matcheKey != null) {
                System.out.println("JSON matcheKey = " + matcheKey);
                System.out.println("JSON matcheVal = " + matcheVal);
            }
            //XML
            matcheKey = matcherJson.group(3);
            matcheVal = matcherJson.group(4);
            if (matcheKey != null) {
                System.out.println("XML matcheKey = " + matcheKey);
                System.out.println("XML matcheVal = " + matcheVal);
            }
        } 
    }
}

相关文章

网友评论

      本文标题:正则表达式同时按Key获取JSON和XML中的多个值

      本文链接:https://www.haomeiwen.com/subject/mfbwrjtx.html