Solved

java regular expression callback ?

Posted on 2012-03-20
2
622 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

914 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now