membersound
membersound

Reputation: 86727

How to replace all numeric characters with a specific value?

I want to replace all numbers inside a string with specific values.

Teststring: -SD12431;ABC333

How can I identify blocks of digits, and especially replace them with a (dynamic) new value?

For example after replacement: -SDfirst;ABCsecond?

Upvotes: 0

Views: 468

Answers (4)

Flavian Jacquot
Flavian Jacquot

Reputation: 51

You can use the replaceFirst(String regex, String replacement) function of the string class.

Look at http://javarevisited.blogspot.fr/2011/12/java-string-replace-example-tutorial.html

So in first argument you have to use a regex for finding digit such as :

  • "[0-9]" will find a single digit
  • "[0-9]+" will find one or more digit

    String testString = "-SD12431;ABC333";
    ArrayList<String> remplaceBy= new ArrayList<String>();
    remplaceBy.add("first");
    remplaceBy.add("second");
    remplaceBy.add("third");
    
    String newString = testString;
    String oldString ="";
    int i =0;
    while(!newString.equals(oldString))
    {
    oldString = new String(newString);
    newString = newString.replaceFirst("[0-9]+",remplaceBy.get(i));
    i++;
    System.out.println("N1:"+newString);
    System.out.println("O1:"+oldString); 
    }
    System.out.println("New String"+newString);
    

Upvotes: -1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

You can do it this way

    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile("\\d+").matcher(str);
    int n = 0;
    while(m.find()) {
        if (++n == 1) {
            m.appendReplacement(sb, "first");
        } else {
            m.appendReplacement(sb, "second");
        }
    }
    m.appendTail(sb);
    s = sb.toString();

Upvotes: 2

Dave Lugg
Dave Lugg

Reputation: 2374

The replaceFirst() method will let you do this if you use it in a loop.

String myNewString = myString.replaceFirst("\\d+","first");

If you loop over the this statement, each invocation of replaceFirst() will replace the first group of digits with whatever you provide as a second argument.

Upvotes: 5

Sarthak Mittal
Sarthak Mittal

Reputation: 6104

You can do something like this:

yourString = yourString.replaceFirst("\\d+",firstString).replaceFirst("\\d+",secondString);  //and so on

or use a loop if it fits your needs better

Upvotes: 1

Related Questions