Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模式不提供预期的输出_Java_Regex - Fatal编程技术网

Java 模式不提供预期的输出

Java 模式不提供预期的输出,java,regex,Java,Regex,我有以下代码: 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

我有以下代码:

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 *
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和3之间有一个空格,但它需要
[-+*/$”
。谢谢你的评论,我似乎需要重新设计我的正则表达式。你需要解析这样的内容吗:
34+45+*
谢谢你这很有效,如果可以的话,我会接受这个回答另一个问题如果我的输入是3 3*4+2/我怎么能得到3 3*而不是3 3*的输出我很抱歉,但是正则表达式从来不是我的强项。基本上,运算符之间可以有任意数量的数字将
更改为
*
,类似于
“\\d+”\\s*[-\\+\*/\\$”
非常感谢您的帮助和耐心
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 /