title: How can I replace strings in a text in Java?
body: <p>In a project we have text files looking like this:</p>
  
  <pre><code>mv A, R3
  mv R2, B
  mv R1, R3
  mv B, R4
  add A, R1
  add B, R1
  add R1, R2
  add R3, R3
  add R21, X
  add R12, Y
  mv X, R2
  </code></pre>
  
  <p>I need to replace the strings according to the following, but I am looking
  for a more general solution.</p>
  
  <pre><code>R1  =&gt; R2
  R2  =&gt; R3
  R3  =&gt; R1
  R12 =&gt; R21
  R21 =&gt; R12
  </code></pre>
  
  <p>I know I could do it in Perl, the replace() function in the following code,
  but the real application is written in Java, so the solution needs to be 
  in Java as well. </p>
  
  <pre><code>#!/usr/bin/perl
  use strict;
  use warnings;
  
  use File::Slurp qw(read_file write_file);
  
  
  my %map = (
      R1  =&gt; 'R2',
      R2  =&gt; 'R3',
      R3  =&gt; 'R1',
      R12 =&gt; 'R21',
      R21 =&gt; 'R12',
  );
  
  replace(\%map, \@ARGV);
  
  sub replace {
      my ($map, $files) = @_;
  
      # Create R12|R21|R1|R2|R3
      # making sure R12 is before R1
      my $regex = join "|",
                  sort { length($b) &lt;=&gt; length($a) }
                  keys %$map;
  
      my $ts = time;
  
      foreach my $file (@$files) {
          my $data = read_file($file);
          $data =~ s/\b($regex)\b/$map{$1}/g;
          rename $file, "$file.$ts";       # backup with current timestamp
          write_file( $file, $data);
      }
  }
  </code></pre>
  
  <p>Your help for the Java implementation would be appreciated.</p>