我有以下代码:
Pattern pattern = Pattern.compile("\\d*\\s*[-\\+\\*/\\$£]");
String input = "3 3 * 4 + 2 /";
Matcher matcher = pattern.matcher(input);
List<String> output = new ArrayList<>();
while (matcher.find()) {
output.add(matcher.group());
}
for(String s : output){
System.out.println(s);
}
我非常希望列表中的输出如下:
3 3 *
4 +
2 /
唉,我的实际输出是:
3 *
4 +
2 /
我确信有一个正则表达式向导可以向我展示这个问题:)
最佳答案
由于两个数字之间存在空格,因此您需要添加一个模式来匹配第二个数字并将其设为可选。我还建议您使用 \d+
而不是 \d*
因为 \d*
也匹配空字符串。
Pattern pattern = Pattern.compile("\\d+(\\s\\d+)?\\s*[-+*/$£]");
String input = "3 3 * 4 + 2 /";
Matcher matcher = pattern.matcher(input);
ArrayList<String> output = new ArrayList<String>();
while (matcher.find()) {
output.add(matcher.group());
}
for(String s : output){
System.out.println(s);
}
输出:
3 3 *
4 +
2 /
关于java - 模式未提供预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600476/