?
Solved

Replace set of characters with another set of characters in a string

Posted on 2011-10-17
15
Medium Priority
?
179 Views
Last Modified: 2012-05-12
can i use the a character sequence in a regex .
For example
If I want to replace '_a' wit A , '_b' with $ then can i use the regex/pattern class to identify if these values _a and _b are there in a String ?
0
Comment
Question by:FranklinRaj22
  • 8
  • 5
  • 2
15 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36982076
sorry, could you explain once more, I'm not sure I understand what is your goal
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36982084
Oh, you mean you want not one character to replace as befire , but rather two charcttyers to replace by one - correct ?
0
 

Author Comment

by:FranklinRaj22
ID: 36982130
exacly ... like _a is a character seq and i want it to be replaced by a single character
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 47

Expert Comment

by:for_yan
ID: 36982190
Strage, this works with _a , but fails with _b (if it is persent in the string)
let me think

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanStrings {






    public static String [] getUpdatedStrings(String [] arr, String s, HashMap<String,String>mm) {
             StringBuffer sb = new StringBuffer();
       Matcher m;
          Pattern p = Pattern.compile(s);
        for(int j=0; j<arr.length; j++){
      m = p.matcher(arr[j]);



           if (!arr[j].matches(".*"+s+".*")) continue;
          sb.delete(0,sb.length());

 while (m.find()) {
     System.out.println("found: " + arr[j].substring(m.start(),m.end()));

     m.appendReplacement(sb, mm.get(m.group(0)) );
 }
 m.appendTail(sb);
         arr[j] = sb.toString();


        }



        return arr;
    }

    public static void main(String[] args) {

        String reg = "(([\\!\\&\\^\\]])|(_b)|(_a))";




        HashMap<String,String> mm = new HashMap<String,String>();
      //  mm.put("$","E");
        mm.put("&","A");
        mm.put("^","C");
        mm.put("]","D");
          mm.put("!","U");
          mm.put("_a","A");
          mm.put("_b","$");

        String [] arr = {"asdasda$as!asda&fasdfsdsd","eter_atertert","erterte_ar^&ertert]erte","sdfsd]]sdfsd6s!dfsdfssd7asdas$","gdfgd888dasdas666asdasd"};

        arr =  getUpdatedStrings(arr,  reg, mm);

        for (String s : arr){
            System.out.println(s);
        }






 }

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36982211
How does this question differ from http:Q_27383828.html please?

I already posted working code (which you ignored) that solves this problem there
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36982213
It actually deso not want to work when I chnage _b to $, whe I cange _b to letter , say "N" it works fine - really starnge
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36982221
$ needs escaping. It's a regex reserved character
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36982228
But it is not in regex, it does not want tow work with iit when $ is in replacement cgharactcetr !
0
 
LVL 47

Accepted Solution

by:
for_yan earned 1000 total points
ID: 36982246
This works fine if I chenge _b to %,
but is i change _B to $ - wwrites an exception - unlbelievable!

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanStrings {






    public static String [] getUpdatedStrings(String [] arr, String s, HashMap<String,String>mm) {
             StringBuffer sb = new StringBuffer();
       Matcher m;
          Pattern p = Pattern.compile(s);
        for(int j=0; j<arr.length; j++){
      m = p.matcher(arr[j]);



           if (!arr[j].matches(".*"+s+".*")) continue;
          sb.delete(0,sb.length());

 while (m.find()) {
     System.out.println("found: " + arr[j].substring(m.start(),m.end()));

     m.appendReplacement(sb, mm.get(m.group(0)) );
 }
 m.appendTail(sb);
         arr[j] = sb.toString();


        }



        return arr;
    }

    public static void main(String[] args) {

        String reg = "(([\\!\\&\\^\\]])|(_b)|(_a))";




        HashMap<String,String> mm = new HashMap<String,String>();
      //  mm.put("$","E");
        mm.put("&","A");
        mm.put("^","C");
        mm.put("]","D");
          mm.put("!","U");
          mm.put("_a","A");
         // mm.put("_b","$");
            mm.put("_b","%");

        String [] arr = {"asdasda$as!asda&fasdfsdsd","eter_atertert","erterte_ar^&ertert]erte","sd_bfsd]]sdfsd6s!dfsdfssd7asdas$","gdfgd888dasdas666asdasd"};

        arr =  getUpdatedStrings(arr,  reg, mm);

        for (String s : arr){
            System.out.println(s);
        }






 }

}

Open in new window



found: !
found: &
found: _a
found: _a
found: ^
found: &
found: ]
found: _b
found: ]
found: ]
found: !
asdasda$asUasdaAfasdfsdsd
eterAtertert
erterteArCAertertDerte
sd%fsdDDsdfsd6sUdfsdfssd7asdas$
gdfgd888dasdas666asdasd

Open in new window

0
 

Author Comment

by:FranklinRaj22
ID: 36982279
CEHJ,

the only diff is that i wanted to know if i can use regex /pattern calsses wen using character seq '_b'
and offcrse ur code was laso wrkin and i never ignored your anwsers .
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 1000 total points
ID: 36982301
mm.put("_b","\\$");
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36982311
>>was laso wrkin and i never ignored your anwsers .

By 'ignored' i mean that i got zero points for them - which amounts to the same thing
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36982356
Inded it seesm it works with replacement "\\$"
but I don't undertstand what connection reoplacement has with
regexes

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanStrings {






    public static String [] getUpdatedStrings(String [] arr, String s, HashMap<String,String>mm) {
             StringBuffer sb = new StringBuffer();
       Matcher m;
          Pattern p = Pattern.compile(s);
        for(int j=0; j<arr.length; j++){
      m = p.matcher(arr[j]);



           if (!arr[j].matches(".*"+s+".*")) continue;
          sb.delete(0,sb.length());

 while (m.find()) {
     System.out.println("found: " + arr[j].substring(m.start(),m.end()));
     System.out.println("group: " + m.group(0));
     System.out.println("mm.get: " + mm.get(m.group(0)));
       //  sb.append(arr[j].substring(0,m.start()) + mm.get(m.group(0)) + arr[j].substring(m.end()));
     m.appendReplacement(sb, mm.get(m.group(0)) );
 }
 m.appendTail(sb);
         arr[j] = sb.toString();


        }



        return arr;
    }

    public static void main(String[] args) {

        String reg = "(([\\!\\&\\^\\]])|(_b)|(_a))";




        HashMap<String,String> mm = new HashMap<String,String>();
      //  mm.put("$","E");
        mm.put("&","A");
        mm.put("^","C");
        mm.put("]","D");
          mm.put("!","U");
          mm.put("_a","A");
          mm.put("_b","\\$");
           // mm.put("_b","%");

        String [] arr = {"asdasda$as!asda&fasdfsdsd","eter_atertert","erterte_ar^&ertert]erte","sd_bfsd]]sdfsd6s!dfsdfssd7asdas","gdfgd888dasdas666asdasd"};

        arr =  getUpdatedStrings(arr,  reg, mm);

        for (String s : arr){
            System.out.println(s);
        }






 }

}

Open in new window



Output (with some debgging iooutput):
found: !
group: !
mm.get: U
found: &
group: &
mm.get: A
found: _a
group: _a
mm.get: A
found: _a
group: _a
mm.get: A
found: ^
group: ^
mm.get: C
found: &
group: &
mm.get: A
found: ]
group: ]
mm.get: D
found: _b
group: _b
mm.get: \$
found: ]
group: ]
mm.get: D
found: ]
group: ]
mm.get: D
found: !
group: !
mm.get: U
asdasda$asUasdaAfasdfsdsd
eterAtertert
erterteArCAertertDerte
sd$fsdDDsdfsd6sUdfsdfssd7asdas
gdfgd888dasdas666asdasd

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36982399
"The replacement string may contain references to subsequences captured during the previous match: Each occurrence of $g will be replaced by the result of evaluating group(g). The first number after the $ is always treated as part of the group reference. "

( http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer, java.lang.String) )

IOW, '$' is reserved and needs escaping
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36982424
Yes, these are the trick of appendReplacement, rather painful
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month16 days, 5 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question