我有一个跟随字符串,我想用正则表达式读取它并将其作为键和值放入映射。我已经拆分并放入映射。但问题是我使用了字符串数组并且那里数组索引的风险很高。所以我认为这种方式不适合良好的编码。
public static void read(String log,Map<String, String> logMap) {
String sanitizeLog = "";
String commaSeparatedLine[];
String equalSeparatedLine[];
String patternComma = ",";
String patternEqual = "=";
String patternSanitize = "(?<=]:).*";
Pattern pattern = Pattern.compile(patternSanitize);
Matcher matcher = pattern.matcher(log);
if (matcher.find()) {
sanitizeLog = matcher.group();
}
pattern = Pattern.compile(patternComma);
commaSeparatedLine = pattern.split(sanitizeLog);
for (String line : commaSeparatedLine) {
pattern = Pattern.compile(patternEqual);
equalSeparatedLine = pattern.split(line);
for (int i = 0; i < equalSeparatedLine.length; i += 2) {
logMap.put(equalSeparatedLine[i].trim(),
equalSeparatedLine[i + 1]);
}
}
}
上面的代码片段运行正常。但是我使用了很多字符串数组来存储分割值。请让我知道有没有办法在不使用字符串数组的情况下执行相同的操作并将分割值放入地图中正则表达式。我是正则表达式的新手。
输出地图应该包含这样的内容。
Key -> value
DB.UPDATE_CT -> 2
DB.DUPQ_CT -> 1
...
要拆分的字符串值
[2015-01-07 07:17:56,911]:R =“InProgressOrders.jsp”,REQUEST_UUID =“77ed2ab1-b799-4715-acd5-e77ab756192e”,HTTP_M =“POST”, PFWD =“login.jsp”,USER_ORG =“TradeCustomer.1717989”,TX_ORG1 =“1717989”, DB.QUERY_CT = 61,DB.UPDATE_CT = 2,DB.DUPQ_CT = 1,DB.SVR_MS = 59, DB.IO_MS = 111,DB.DRV_MS = 144,DB.LOCK_MS = 31,DB.BYTES_W = 1501,KV.PUT = 1, KV.GET = 5,KV.PWAIT_MS = 2,KV.GWAIT_MS = 4,KV.BYTES_W = 193, KV.BYTES_R = 367,MCACHE.GET = 30,MCACHE.PUT = 18,MCACHE.L1HIT = 10, MCACHE.L2HIT = 1,MCACHE.HIT = 1,MCACHE.MISS = 18,MCACHE.WAIT_MS = 51, MCACHE.BYTES_W = 24538,MCACHE.BYTES_R = 24282,ROOTS.READ_CT = 6, ROOTS.DUPRSV_CT = 3,THREAD.WALL_MS = 594,THREAD.CPU_MS = 306, THREAD.CPU_USER_MS = 300,THREAD.MEM_K = 19318
答案 0 :(得分:1)
你似乎有很多代码。以下是如何在1行中进行的操作:
Map<String, String> map = Arrays.stream(input.split(","))
.map(s -> a.split("="))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
要将条目添加到另一个地图(如代码中):
Arrays.stream(input.split(",")).map(s -> a.split("="))
.forEach(a -> logMap.put(a[0], a[1]));
免责声明:未经测试或编译,只是翻阅了。