Solved

java regular expression callback ?

Posted on 2012-03-20
2
629 Views
Last Modified: 2012-03-20
Hi,

Goal: prefix each number in a string with 1-5 zeros depending on the number
e.g. if it's less than 10 then prepend 4 zeros, if it's two digits then prefix three zeros.
This basically prefixes each number with zeros so each number is 5 digits.

Source
String str = "1 - test 86";

Desired Result:
String str = "00001 - test 00086";

I've tried this but this adds zeros to every number
str = str .replaceAll("(\\d+)", "00000$1");

any ideas?
0
Comment
Question by:svetoslavm
2 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 37741317
             String s900 = "1 - test 86";


   Pattern pp = Pattern.compile("\\d+");



        Matcher m900 = pp.matcher(s900);


        StringBuffer sb = new StringBuffer();
 while (m900.find()) {
     String s701 = s900.substring(m900.start(),m900.end());
     while(s701.length()<5)s701="0"+s701;
     m900.appendReplacement(sb, s701);
 }
 m900.appendTail(sb);
                         System.out.println(sb.toString());

Open in new window


Output:

00001 - test 00086

Open in new window

0
 

Author Closing Comment

by:svetoslavm
ID: 37741336
thanks!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

770 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