我是 Java 新手,我有一个文本文件,其中包含如下信息:
1.Store 123 has cloth style B.
2.Store 253 has cloth style D.
3.Store 27 has cloth style A.
4.Store 164 has cloth style F.
......
然后我尝试将有用的信息(仅存储编号和样式编号)放入集合中并打印出来,集合应该是这样的:
[123 B, 253 D, 27 A, 164 F, ...]
我尝试过这个:
Set<String> setStoreStyle = new HashSet<String>();
Pattern patternStoreStyle = Pattern.compile("Store (.+?) has cloth style(.+?).");
FileInputStream fstream = new FileInputStream(MyTextfilePath);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
for (String line = br.readLine(); line != null; line = br.readLine()){
Matcher matcherStoreStyle = patternStoreStyle.matcher(line);
if(matcherStoreStyle.find()){
String a = matcherStoreStyle.group(1);
setStoreStyle.add(a);
}
}
br.close();
System.out.println(setStoreStyle);
但我刚刚得到
[123, 253, 27, 164, ...]
有什么解决办法吗?
最佳答案
您访问第一个捕获组,但不能访问第二个:
String a = matcherStoreStyle.group(1) + " " + matcherStoreStyle.group(2);
此外,正如 @WictorStribizew 所指出的,您应该转义模式中的最后一个 .
,以便它匹配文字句点,而不是任何字符。
关于java表达式查找多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336858/