-1

I have started to learn regex since I have found it very usefull.

I have a task which I am trying to solve but my output fails. Read two files from keyboard, read first file and change all dots to exclamation marks and save the content of first file to second file. My solution:

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String file1 = reader.readLine();
        String file2 = reader.readLine();
        reader.close();

        FileReader fileReader = new FileReader(file1);
        FileWriter fileWriter = new FileWriter(file2);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        String a;
        while ((a = bufferedReader.readLine()) != null) {
            a.replaceAll("\\.","\\!");
            bufferedWriter.write(a);
        }

        bufferedReader.close();
        bufferedWriter.close();
    }
}
3
  • 1
    a = a.replace(".","!"); if you need to replace a dot with !, mind strings are immutable. Commented May 8, 2020 at 11:18
  • a = a.replaceAll("\\.","!"); Commented May 8, 2020 at 11:19
  • Oh God, I never noticed that. Thanks it worked! Commented May 8, 2020 at 11:19

1 Answer 1

0

I don't think the backslashes are needed. Try just . and !.

Sign up to request clarification or add additional context in comments.

1 Comment

It won't work in OP code. OP is using .replaceAll and if you remove the \ before . it will match any char but line break chars.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.