[java] 자바; 문자열 바꾸기 (정규 표현식 사용)?

학교 프로젝트의 일부로 다음 형식의 문자열을 바꿔야합니다.

5 * x^3 - 6 * x^1 + 1

다음과 같이 :

5x<sup>3</sup> - 6x<sup>1</sup> + 1

정규 표현식으로 할 수 있다고 생각하지만 아직 어떻게해야할지 모르겠습니다.

도와 줄 수 있나요?

추신 실제 할당은 다항식 처리 Java 응용 프로그램을 구현하는 것이며, 이것을 사용하여 모델에서 뷰로 polynomial.toString ()을 전달하고 있으며 html 태그를 사용하여 예쁘게 표시하고 싶습니다.



답변

str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");


답변

private String removeScript(String content) {
    Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    return p.matcher(content).replaceAll("");
}


답변

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");


답변

import java.util.regex.PatternSyntaxException;

// (:?\d+) \* x\^(:?\d+)
// 
// Options: ^ and $ match at line breaks
// 
// Match the regular expression below and capture its match into backreference number 1 «(:?\d+)»
//    Match the character “:” literally «:?»
//       Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
//    Match a single digit 0..9 «\d+»
//       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character “ ” literally « »
// Match the character “*” literally «\*»
// Match the characters “ x” literally « x»
// Match the character “^” literally «\^»
// Match the regular expression below and capture its match into backreference number 2 «(:?\d+)»
//    Match the character “:” literally «:?»
//       Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
//    Match a single digit 0..9 «\d+»
//       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
try {
    String resultString = subjectString.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
    // Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
    // Non-existent backreference used the replacement text
}


답변

"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");

단일 정규식 / 대체에서 두 대체를 결합하는 것은 x^3 - 6 * x실패 와 같은보다 일반적인식이 기 때문에 잘못된 선택 입니다.


답변

이것이 일반적인 수학 표현식이고 괄호 표현식이 허용되는 경우 정규 표현식으로이를 수행하는 것이 매우 어렵습니다 (아마도 불가능할 것입니다).

당신이 보여준 것이 유일한 대체품이라면 그렇게 어렵지 않습니다. 먼저 *‘s를 제거한 다음 Can Berk Güder가 ^‘s 를 처리하기 위해 보여준 것처럼 캡처를 사용 합니다.


답변

다항식은 무엇입니까? 당신이 그것을 “처리”한다면, 나는 어떤 시점에서 생성되는 일종의 하위 표현의 트리를 구상하고 있으며, 원시를 다시 파싱하는 것보다 문자열을 생성하는 데 사용하는 것이 훨씬 더 간단 할 것이라고 생각할 것입니다. 정규식으로 표현.

그냥 다른 사고 방식을 던지고 있습니다. 앱에서 다른 일이 일어나고 있는지 잘 모르겠습니다.