자바; 문자열 대체 (정규 표현식 사용)?
학교 프로젝트의 일환으로 양식에서 문자열을 교체해야합니다.
5 * x^3 - 6 * x^1 + 1
같은 것 :
5x<sup>3</sup> - 6x<sup>1</sup> + 1
정규 표현식 으로이 작업을 수행 할 수 있다고 생각하지만 아직 수행 방법을 모르겠습니다.
손 좀 빌려 줄 수 있어요?
추신 실제 할당은 Polynomial Processing 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입니다.
이것이 일반적인 수학 표현을위한 것이고 괄호로 표현되는 것이 허용된다면, 정규 표현식으로 이것을하는 것은 매우 어려울 것입니다 (아마도 불가능할 것입니다).
If the only replacements are the ones you showed, it's not that hard to do. First strip out *'s, then use capturing like Can Berk Güder showed to handle the ^'s.
What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.
Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.
class Replacement
{
public static void main(String args[])
{
String Main = "5 * x^3 - 6 * x^1 + 1";
String replaced = Main.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
System.out.println(replaced);
}
}
You'll want to look into capturing in regex to handle wrapping the 3 in ^3.
Try this:
String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");
Be sure to import java.util.regex.
Try this, may not be the best way. but it works
String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);
Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.
https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)
In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.
참고URL : https://stackoverflow.com/questions/632204/java-string-replace-using-regular-expressions
'Programing' 카테고리의 다른 글
| ggplot을 사용하여 축의 숫자 형식을 어떻게 변경합니까? (0) | 2020.07.27 |
|---|---|
| android에서 adjustResize와 adjustPan의 차이점은 무엇입니까? (0) | 2020.07.27 |
| 반복하는 동안 HashSet에서 요소 제거 (0) | 2020.07.27 |
| 해시의 값을 기준으로 해시 배열을 어떻게 정렬합니까? (0) | 2020.07.27 |
| null + true는 어떻게 문자열입니까? (0) | 2020.07.27 |