我能够从文件中读取内容
(abcd, 01)
(xyz,AB)
(pqrst, 1E)
我想将此内容保存为map
Map<String, String> map=new HashMap<>();
map.put("abcd","01");
map.put("xyz","AB");
map.put("pqrst","1E");
帮助我使用java中的正则表达式将内容作为Map获取
答案 0 :(得分:0)
我假设您可以使用BufferedReader.readLine()
或类似内容阅读每一行。调用字符串line
。然后放下括号:
line = line.substring(1,line.length()-1);
然后你想要的就是分裂:
String[] bits = line.split(",");
map.put(bits[0], bits[1]);
答案 1 :(得分:0)
问题是关于使用regexp,但假设这不是类赋值等,解决方案并不需要regexp。一个简短的解决方案,也可以处理每个键的多个值:
Map<String, List<String>> map = Files.lines(Paths.get("data.txt")).map(s -> s.replace("(", "").replace(")", ""))
.collect(groupingBy(s -> (s.split(","))[0], mapping(s -> (s.split(",", -1))[1].trim(), toList())));
System.out.println(map);
将生成的地图打印为:
{xyz=[AB], pqrst=[1E], abcd=[01]}
说明:
Files.lines(...) //reads all lines from file as a java 8 stream
map(s-> s.replace) // removes all parenthesis from each line
collect(groupingBy(s -> (s.split(","))[0] //collect all elements from the stream and group them by they first part before the ","
mapping(mapping(s -> (s.split(",", -1))[1].trim(), toList()) //and the part after the "," should be trimmed, -1 makes it able to handle empty strings, collect those into a list as the value of the previously grouping
替代替换,而不是两个简单的替换删除(和)你可以使用
s.replaceAll("\\(|\\)", "")
不确定哪个最具可读性。
答案 2 :(得分:0)
Pattern pattern = Pattern.compile("^\\(([a-z]+), ([0-9A-Z]+)\\)$");
Map<String, String> map = Files.lines(path)
.map(pattern::matcher)
.collect(toMap(x -> x.group(1), x -> x.group(2)));
匹配组1是[a-z]+
- 键。
匹配组2是[0-9A-Z]+
- 值。
根据您的需求更改组模式。
注意:正则表达式是一种强大的机制。如果或者说正确的话,当您的输入数据变得复杂时 - 您的模式将会增长并变得难以理解。