Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 89335
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T22:42:01+00:00 2026-05-10T22:42:01+00:00

In a project we have text files looking like this: mv A, R3 mv

  • 0

In a project we have text files looking like this:

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 

I need to replace the strings according to the following, but I am looking for a more general solution.

R1  => R2 R2  => R3 R3  => R1 R12 => R21 R21 => R12 

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.

#!/usr/bin/perl use strict; use warnings;  use File::Slurp qw(read_file write_file);   my %map = (     R1  => 'R2',     R2  => 'R3',     R3  => 'R1',     R12 => 'R21',     R21 => '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) <=> 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);     } } 

Your help for the Java implementation would be appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T22:42:02+00:00Added an answer on May 10, 2026 at 10:42 pm

    I’ve actually had to use this sort of algorithm several times in the past two weeks. So here it is the world’s second-most verbose language…

    import java.util.HashMap; import java.util.regex.Pattern; import java.util.regex.Matcher;  /* R1  => R2 R2  => R3 R3  => R1 R12 => R21 R21 => R12 */  String inputString      = 'mv A, R3\n'     + 'mv R2, B\n'     + 'mv R1, R3\n'     + 'mv B, R4\n'     + 'add A, R1\n'     + 'add B, R1\n'     + 'add R1, R2\n'     + 'add R3, R3\n'     + 'add R21, X\n'     + 'add R12, Y\n'     + 'mv X, R2'     ;  System.out.println( 'inputString = \'' + inputString + '\'' );  HashMap h = new HashMap(); h.put( 'R1',  'R2' ); h.put( 'R2',  'R3' ); h.put( 'R3',  'R1' ); h.put( 'R12', 'R21' ); h.put( 'R21', 'R12' );  Pattern      p       = Pattern.compile( '\\b(R(?:12?|21?|3))\\b'); Matcher      m       = p.matcher( inputString ); StringBuffer sbuff   = new StringBuffer(); int          lastEnd = 0; while ( m.find()) {     int mstart = m.start();     if ( lastEnd < mstart ) {          sbuff.append( inputString.substring( lastEnd, mstart ));     }     String key   = m.group( 1 );     String value = (String)h.get( key );     sbuff.append( value );     lastEnd = m.end(); } if ( lastEnd < inputString.length() ) {      sbuff.append( inputString.substring( lastEnd )); }  System.out.println( 'sbuff = \'' + sbuff + '\'' ); 

    This can be Java-ified by these classes:

    import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern;  interface StringReplacer {      public CharSequence getReplacement( Matcher matcher ); }  class Replacementifier {       static Comparator keyComparator = new Comparator() {           public int compare( Object o1, Object o2 ) {              String s1   = (String)o1;              String s2   = (String)o2;              int    diff = s1.length() - s2.length();              return diff != 0 ? diff : s1.compareTo( s2 );          }     };     Map replaceMap = null;      public Replacementifier( Map aMap ) {          if ( aMap != null ) {              setReplacements( aMap );          }     }      public setReplacements( Map aMap ) {          replaceMap = aMap;     }      private static String createKeyExpression( Map m ) {          Set          set = new TreeSet( keyComparator );         set.addAll( m.keySet());         Iterator     sit = set.iterator();         StringBuffer sb  = new StringBuffer( '(' + sit.next());          while ( sit.hasNext()) {              sb.append( '|' ).append( sit.next());         }         sb.append( ')' );         return sb.toString();     }      public String replace( Pattern pattern, CharSequence input, StringReplacer replaceFilter ) {         StringBuffer output  = new StringBuffer();         Matcher      matcher = pattern.matcher( inputString );         int          lastEnd = 0;         while ( matcher.find()) {             int mstart = matcher.start();             if ( lastEnd < mstart ) {                  output.append( inputString.substring( lastEnd, mstart ));             }             CharSequence cs = replaceFilter.getReplacement( matcher );             if ( cs != null ) {                  output.append( cs );             }             lastEnd = matcher.end();         }         if ( lastEnd < inputString.length() ) {              sbuff.append( inputString.substring( lastEnd ));         }     }      public String replace( Map rMap, CharSequence input ) {         // pre-condition         if ( rMap == null && replaceMap == null ) return input;          Map     repMap = rMap != null ? rMap : replaceMap;         Pattern pattern               = Pattern.compile( createKeyExpression( repMap ))             ;         StringReplacer replacer = new StringReplacer() {              public CharSequence getReplacement( Matcher matcher ) {                 String key   = matcher.group( 1 );                 return (String)repMap.get( key );             }         };         return replace( pattern, input, replacer );      } } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.