Java 爪哇; 字符串替换(使用正则表达式)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/632204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java; String replace (using regular expressions)?
提问by Dan Burzo
As part of a project for school, I need to replace a string from the form:
作为学校项目的一部分,我需要从表单中替换一个字符串:
5 * x^3 - 6 * x^1 + 1
to something like:
类似于:
5x<sup>3</sup> - 6x<sup>1</sup> + 1
I believe this can be done with regular expressions, but I don't know how to do it yet.
我相信这可以用正则表达式来完成,但我还不知道该怎么做。
Can you lend me a hand?
你能帮我一把吗?
P.S. The actual assignment is to implement a Polynomial Processing Java application, and I'm using this to pass polynomial.toString() from the model to the view, and I want do display it using html tags in a pretty way.
PS 实际的任务是实现一个 Polynomial Processing Java 应用程序,我使用它来将 polynomial.toString() 从模型传递到视图,我想以一种漂亮的方式使用 html 标签来显示它。
回答by Can Berk Güder
str.replaceAll("\^([0-9]+)", "<sup></sup>");
回答by Ryan Graham
You'll want to look into capturing in regex to handle wrapping the 3 in ^3.
您将需要研究在正则表达式中捕获以处理将 3 包装在 ^3 中。
回答by Lieven Keersmaekers
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+)", "x<sup></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
}
回答by Michael Myers
If this is for any general math expression and parenthetical expressions are allowed, it will be very difficult (perhaps impossible) to do this with regular expressions.
如果这是用于任何通用数学表达式并且允许使用括号表达式,则使用正则表达式将非常困难(可能不可能)做到这一点。
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.
如果唯一的替代品是您展示的替代品,那么这并不难。首先*
去掉 's,然后像 Can Berk Güder 展示的那样使用捕获来处理^
's。
回答by cdmckay
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.
请务必导入 java.util.regex。
回答by Adam Jaskiewicz
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.
只是抛出一种不同的思维方式。我不确定您的应用程序中还发生了什么。
回答by Hubbison
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></b>");
回答by BigGinDaHouse
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+)", "x<sup></sup>");
System.out.println(replaced);
}
}
回答by Florian
private String removeScript(String content) {
Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
return p.matcher(content).replaceAll("");
}
回答by user5915163
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+?)", "<sup></sup>");
System.out.println(str);