作为学校项目的一部分,我需要从表单中替换一个字符串:
5 * x^3 - 6 * x^1 + 1
Run Code Online (Sandbox Code Playgroud)
类似于:
5x<sup>3</sup> - 6x<sup>1</sup> + 1
Run Code Online (Sandbox Code Playgroud)
我相信这可以用正则表达式来完成,但我还不知道该怎么做.
你能借给我一个手吗?
PS实际的分配是实现一个多项式处理Java应用程序,我用它来将多项式.toString()从模型传递给视图,我希望以一种漂亮的方式使用html标签显示它.
Can*_*der 159
str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");
Run Code Online (Sandbox Code Playgroud)
小智 34
private String removeScript(String content) {
Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
return p.matcher(content).replaceAll("");
}
Run Code Online (Sandbox Code Playgroud)
小智 19
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>");
Run Code Online (Sandbox Code Playgroud)
Lie*_*ers 10
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
}
Run Code Online (Sandbox Code Playgroud)
小智 8
"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");
Run Code Online (Sandbox Code Playgroud)
请注意,在单个正则表达式/替换中加入两个替换项将是一个糟糕的选择,因为更多的通用表达式x^3 - 6 * x
会失败.
归档时间: |
|
查看次数: |
400371 次 |
最近记录: |