我想使用的格式是这样的替换文本:如何使用输出中的输入部分替换文本?
Text Input: (/ 5 6) + (/ 8 9) - (/ 12 3)
Pattern: (/ %s1 %s2)
Replacement: (%s1/%s2)
Result: (5/6) + (8/9) - (12/3)
有没有一种方法可以轻松地做到这一点?我查看了Java API,但找不到除字符串格式之外的任何东西(与此类型不匹配)和正则表达式(它们不允许我使用输入的匹配部分作为输出的一部分)
我想使用的格式是这样的替换文本:如何使用输出中的输入部分替换文本?
Text Input: (/ 5 6) + (/ 8 9) - (/ 12 3)
Pattern: (/ %s1 %s2)
Replacement: (%s1/%s2)
Result: (5/6) + (8/9) - (12/3)
有没有一种方法可以轻松地做到这一点?我查看了Java API,但找不到除字符串格式之外的任何东西(与此类型不匹配)和正则表达式(它们不允许我使用输入的匹配部分作为输出的一部分)
试试这个:
String input = "(/ 5 6) + (/ 8 9) - (/ 12 3)";
String result = input.replaceAll("\\(/ (\\d+) (\\d+)\\)", "($1/$2)");
这是假设你%s
群体是数字,但它可以很容易地扩展为更复杂的集团模式。
对于更复杂的替代品,你可以在代码检查每一个匹配的模式:
import java.util.regex.*;
Pattern pattern = Pattern.compile("\\(/ (\\d+) (\\d+)\\)");
Matcher m = pattern.matcher(input);
StringBuffer result = new StringBuffer();
while (m.find())
{
String s1 = m.group(1);
String s2 = m.group(2);
// either:
m.appendReplacement(result, "($1/$2)");
// or, for finer control:
m.appendReplacement(result, "");
result.append("(")
.append(s1)
.append("/")
.append(s2)
.append(")");
// end either/or
}
m.appendTail(result);
return result.toString();
要处理更通用的模式,在@rolfl's answer看这个问题。
正则表达式和String.replaceAll(regex, replacement)
就是答案。
的正则表达式是不适合心脏佯攻,但你会是这样的:
String result = input.replaceAll(
"\\(\\s*(\\p{Punct})\\s+(\\d+)\\s+(\\d+)\\)",
"($2 $1 $3)");
编辑....阿德里安的答案是“约”和我一样,也更适合你。我的答案假定'/'字符是任何'标点符号'字符,应该复制到结果中,而不是仅处理'/'。
从技术上讲,你可能想要的东西,如[-+/*]
更换\p{Punct}
(请注意,“ - ”必须始终是第一位的),如果你只想数学运算符。
OK,工作示例:
public static void main(String[] args) {
String input = "(/ 5 6) + (/ 8 9) - (/ 12 3)";
String regex = "\\(\\s*(\\p{Punct})\\s+(\\d+)\\s+(\\d+)\\)";
String repl = "($2 $1 $3)";
String output = input.replaceAll(regex, repl);
System.out.printf("From: %s\nRegx: %s\nRepl: %s\nTo : %s\n",
input, regex, repl, output);
}
产地:
From: (/ 5 6) + (/ 8 9) - (/ 12 3)
Regx: \(\s*(\p{Punct})\s+(\d+)\s+(\d+)\)
Repl: ($2 $1 $3)
To : (5/6) + (8/9) - (12/3)
正则表达式可以处理它;请参阅http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html – 2013-05-06 23:08:11