정규식을 사용하여 표현식이 포함 된 문자열에서 숫자와 연산자를 가져 오려고합니다. 그것은 숫자를 찾았지만 연산자를 찾지 못했습니다. 문자열의 시작 부분에 매치 (숫자 또는 연산자)가 끝나면 다음 식을 찾으려면 식을 자릅니다.Java Regex 찾기 연산자
String expression = "23*12+11";
Pattern intPattern;
Pattern opPattern;
Matcher intMatch;
Matcher opMatch;
intPattern = Pattern.compile("^\\d+");
intMatch = intPattern.matcher(expression);
opPattern = Pattern.compile("^[-+*/()]+");
opMatch = opPattern.matcher(expression);
while (! expression.isEmpty()) {
System.out.println("New expression: " + expression);
if (intMatch.find()) {
String inputInt = intMatch.group();
System.out.println(inputInt);
System.out.println("Found at index: " + intMatch.start());
expression = expression.substring(intMatch.end());
intMatch = intPattern.matcher(expression);
System.out.println("Truncated expression: " + expression);
} else if (opMatch.find()) {
String nextOp = opMatch.group();
System.out.println(nextOp);
System.out.println("Found at index: " + opMatch.start());
System.out.println("End index: " + opMatch.end());
expression = expression.substring(opMatch.end());
opMatch = opPattern.matcher(expression);
System.out.println("Truncated expression: " + expression);
} else {
System.out.println("Last item: " + expression);
break;
}
}
출력은 문자 클래스 내부에 있기 때문에 *, + 특수 문자를 이스케이프 할 필요가 없습니다 지금까지 내가 조사 할 수 있었다으로
New expression: 23*12+11
23
Found at index: 0
Truncated expression: *12+11
New expression: *12+11
Last item: *12+11
입니다. 여기서 뭐가 문제 야?
를 놓쳤다. 별도의 스캐너 및 파서를 작성해야합니다. – EJP
네, 저도 그것에 대해 읽었습니다. 그러나 나는 그것을 어떻게하는지 정말로 모른다. Regex 나는 python과 sed로부터 알고있다. 어쨌든, 정규식이 작동 한 이후로 문제는 무엇입니까? – loxosceles