Solved

java regular expression callback ?

Posted on 2012-03-20
2
615 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
Comment Utility
             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
Comment Utility
thanks!
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

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…
I have been reconstructing a PHP-based application that has grown into a full blown interface system over the last ten years by a developer that has now gone into business for himself building websites. I am not incredibly fond of writing PHP code o…
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:
The viewer will learn how to implement Singleton Design Pattern in Java.

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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now