【发布时间】:2021-08-08 09:11:55
【问题描述】:
我正在尝试匹配子字符串和键值对。例如,匹配字符串:
"\"a,b,c\",,\"$a = test1, $1 = test2, $2 = test2\",3\n"一个
应该返回
a test1
1 test2
2 test2
a
b
c
在哪里
a test1
2 test2
是地图,a,b,c 是 List 的项目。
以下代码:
import javafx.util.Pair;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class KeyValuesExtract {
private Pair<List<String>, Map<String, String>> getKeyValues(final String line) {
final Pattern quotesPattern = Pattern.compile("\"(.*?)\"");
final Matcher quotesMatcher = quotesPattern.matcher(line);
quotesMatcher.find();
final List<String> vids = Arrays.asList(quotesMatcher.group(0).split(",")).stream().map(x ->
x.replace("\"", "").trim()).collect(Collectors.toList());
final Map<String, String> enumKeyValuePairs = new HashMap<>();
final Pattern keyValuePattern = Pattern.compile("\"\\$([A-Za-z0-9]+)\\s=\\s(\\w+)(?:,\\s\\$([A-Za-z0-9]+)\\s=\\s(\\w+))*\"");
final Matcher keyValueMatcher = keyValuePattern.matcher(line);
while (keyValueMatcher.find()) {
for (int i = 1; i <= keyValueMatcher.groupCount(); i++) {
enumKeyValuePairs.put(keyValueMatcher.group(i), keyValueMatcher.group(++i));
}
}
return new Pair(vids, enumKeyValuePairs);
}
public static void main(String args[]) {
final String str = "\"a,b,c\",,\"$a = test1, $1 = test2, $2 = test2\",3\n";
final KeyValuesExtract testCode = new KeyValuesExtract();
final Pair<List<String>, Map<String, String>> pair = testCode.getKeyValues(str);
pair.getValue().entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});
pair.getKey().forEach(entry -> {
System.out.println(entry);
});
}
}
打印:
a test1
2 test2
a
b
c
从一个较早的问题:Extracting key value pair from substring within string我已经更新了正则表达式
"\"\\$(\\d+)\\s=\\s(\\w+)(?:,\\s\\$(\\d+)\\s=\\s(\\w+))*\""
同时匹配数字和字符:
"\"\\$([A-Za-z0-9]+)\\s=\\s(\\w+)(?:,\\s\\$([A-Za-z0-9]+)\\s=\\s(\\w+))*\""
如何匹配所有 Map 值? :
a test1
1 test2
2 test2
【问题讨论】: