import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class hw2 {
static char[] evaluate(String input) throws IllegalArgumentException
{
input = input.replaceAll("\\p{Z}", "");
String result_num1 = null;
String result_op = null;
String result_num2 = null;
Pattern pattern_num = Pattern.compile("([+-][0-9]*)([+-/*])([+-]\\d*)");
Matcher matcher_num = pattern_num.matcher(input);
while(matcher_num.find()) {
result_num1 = matcher_num.group(1);
result_op = matcher_num.group(2);
result_num2 = matcher_num.group(3);
}
System.out.println(result_num1);
System.out.println(result_op);
System.out.println(result_num2);
return element_2;
}
public static void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
String input = reader.readLine();
char[] result = evaluate(input);
System.out.println(result);
}
}
有人可以指导一下吗?
输入:300 + 25
预期输出:
300
+
25
+
输出:
空
空
空
最佳答案
根据您显示的示例,您可以尝试以下操作吗?
([+-]?\\d+)([-+/*])([+-]?\\d+)
说明:为上述内容添加详细说明。
([+-]?\\d+) ##Creating first group which checks if there is either +/- present(as optional) following with 1 or more occurrences.
([-+/*]) ##Creating 2nd group and checking if +/- or / is present
([+-]?\\d+) ##Creating 3rd group which checks if there is either +/- present(as optional) following with 1 or more occurrences.
关于Java 正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66657372/