Home > database >  String.replaceAll() doesn't work on some files and strings
String.replaceAll() doesn't work on some files and strings

Time:05-22

This is the code:

public static void update(String stringOld, String stringNew, String strPath) {
    Path path = Paths.get(strPath);
    Charset charset = StandardCharsets.UTF_8;
    try {
        String content = new String(Files.readAllBytes(path), charset);
        content = content.replaceAll(stringOld, stringNew);
        Files.write(path, content.getBytes(charset));
    } catch (IOException e) {
        System.out.println("\n\nERRORE: "   e.getMessage()   "\n");
    }
}

stringOld:

IDX=8, Tipo=Auto, Marca= , Modello= , Versione= , Anno=2002, Potenza(CV)=200, Cambio=Manuale, Carburante=Benzina, Posti=20, Porte=5, Colore=gkgdl, Condizione=Nuovo, Prezzo=4500;

stringNew:

IDX=8, Tipo=Auto, Marca=Maserati, Modello=Levante, Versione=Gransport, Anno=2020, Potenza(CV)=250, Cambio=Automatico, Carburante=Diesel, Posti=5, Porte=5, Colore=Bianca, Condizione=KM0, Prezzo=75000;

Output:

...; 
IDX=8, Tipo=Auto, Marca= , Modello= , Versione= , Anno=2002, Potenza(CV)=200, Cambio=Manuale, Carburante=Benzina, Posti=20, Porte=5, Colore=gkgdl, Condizione=Nuovo, Prezzo=4500;
...;

The string stringOld matches a line in the file but is not replaced with stringNew. If I use the same method with another string and on another file it works fine

CodePudding user response:

The parentheses in your 'oldString' are special characters within a regular expression used for grouping. Therefore it doesn't match.

You can test by pasting your text and regex here or other online tools.

You should actually escape your brackets by add a backslash in front of it. => Potenza\(CV\)=200

CodePudding user response:

If you want to use string instead of regex as source, use:

String.replace(CharSequence,CharSequence)
  • Related