Search code examples
javaregexreplaceall

Replace a million different regex of a string


I'm doing a million different regex replacements of a string. Thus I decided to save all String regex's and String replacements in a file.txt. I tried reading the file line by line and replacing it but it is not working.

replace_regex_file.txt

aaa   zzz
^cc   eee
ww$   sss
...
...
...
...
a million data

Coding

String user_input = "assume 100,000 words"; // input from user
String regex_file = "replace_regex_file.txt"; 
String result="";
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(regex_file)) {
   while ((line = reader.readLine()) != null) { // while line not equal null
      String[] parts = line.split("\\s+", 2); //split process
      if (parts.length >=2) {
         String regex = parts[0]; // String regex stored in first array
         String replace = parts[1]; // String replacement stored in second array
         result = user_input.replaceAll(regex, replace); // replace processing
      }
   }
} System.out.println(result); // show the result

But it does not replace anything. How can I fix this?


Solution

  • Your current code will only apply the last matching regex, because you don't assign the result of the replacement back to the input string:

    result = user_input.replaceAll(regex, replace);
    

    Instead, try:

    String result = user_input;
    

    outside the loop and

    result = result.replaceAll(regex, replace);