?
Solved

java regular expression callback ?

Posted on 2012-03-20
2
Medium Priority
?
651 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month9 days, 7 hours left to enroll

762 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