我的代码不想工作。我想替换所有逗号,但替换这些逗号",",这},{
import java.io.*;
public class converter {
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(
new FileReader("C:/Users/Sei_Erfolgreich/Desktop/convert.txt"));
String zeile;
try {
File newTextFile = new File("C:/Users/Sei_Erfolgreich/Desktop/convert2.txt");
FileWriter fw = new FileWriter(newTextFile);
while ((zeile = br.readLine()) != null) {
zeile = zeile.replaceAll("","", "uffff").replaceAll(",", "").replaceAll("uffff", "","")
.replaceAll("uffff", "},{")
.replaceAll("},{", "uffff");
System.out.println(zeile);
fw.write(zeile);
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
所以我想让这个逗号留在},{
之间,但它不起作用,我收到一条错误消息"Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1 },{
"
replaceAll()
方法采用正则表达式而不是正则字符串。大括号在 Java 正则表达式中具有特殊含义。
您必须转义大括号,否则它们将被理解为正则表达式的一部分。
但是,以下表达式将无法正常工作:
zeile.replaceAll("","", "uffff")
.replaceAll(",", "")
.replaceAll("uffff", "","")
.replaceAll("uffff", "},{")
.replaceAll("},{", "uffff");
因为您正在使用多个 replaceAll()
调用,所以您正在生成多个中间结果,并且结果取决于前面的中间结果。
例如,如果输入字符串的内容将被",",},{
,您的程序将:
1. zeile.replaceAll("","", "uffff") // input = uffff,},{
2. .replaceAll(",", "") // input = uffff}{
3. .replaceAll("uffff", "","") // input = ","}{
4. .replaceAll("uffff", "},{") // input = ","}{
5. .replaceAll("\},\{", "uffff"); // input = ","}{
笔记:
- 请注意,第 1 行和第 3 行正在执行反向更改,首先您将所有出现的
","
替换为uffff
,然后只需将它们全部替换回去 - 第 4 行永远不会执行,因为第 3 行中已经替换了所有
uffff
- 第 5 行也永远不会执行,因为第 2 行中已经替换了
,
的所有出现
{
和}
在正则表达式(量词)中具有特殊含义。使用 转义这些字符。
使用第二个对 Java 进行转义。
结果:.replaceAll("\},\{", "\uffff");
更新
更改替换顺序,如下所示:
zeile = zeile.replaceAll("","", "uffff") //backup any ","
.replaceAll("\},\{", "ueeee") //backup any },{
.replaceAll(",", "") //replace all commas that are still in the string
.replaceAll("uffff", "","") //restore ","
.replaceAll("ueeee", "},{"); //restore },{