Solved

java regular expression callback ?

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Do you hate spam? I do, and I am willing to bet you do as well. I often wonder, though, "if people hate spam so much, why do they still post their email addresses on the web?" I'm not talking about a plain-text posting here. I am referring to the fa…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

733 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