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);
}
}
}
}