How add 0 in front of every single digit of a stri

2019-08-08 15:40发布

问题:

Given a string such as

September 3  September 3  September 2  September 1 September 10 August 14

I want to have an output of

September 03  September 03  September 02  September 01 September 10 August 14

Tried some regular expressions with no luck :/

回答1:

use this simple pattern

\b(\d)\b

and replace w/

0$1

Demo

#    \b(\d)\b
\b              # <word boundary>
(               # Capturing Group (1)
  \d            # <digit 0-9>
)               # End of Capturing Group (1)
\b              # <word boundary>


回答2:

You could try finding only numbers which are single digit ones. Then you can replace them with themselves preceded by zero. Your code can look like

text = text.replaceAll("(?<!\\d)\\d(?!\\d)", "0$0");

I used lookaroud mechanisms (?<!\\d) (?!\\d) to make sure that digit we find \d has no other digits before or after.
Replacement 0$0 contains 0 literal and $0 which is reference to group 0 - match found by our regex.

But if you are responsible for generating this text

September 3  September 3  September 2  September 1 September 10 August 14

from smaller parts September 3 September 3 September 2 September 1 September 10 August 14 then maybe consider using String formatter to create this parts with this additional 0 like

String part = String.format("%s %02d","September",3);
System.out.println(part); //September 03


回答3:

Hope below Snippet helps. This is a quick and dirty solution though :)

String currentDate = "September 3";
        String month = "", date = "";

        String tokens[] = currentDate.split(" ");
        StringTokenizer st = new StringTokenizer(currentDate);
        int count = 0;
        while (st.hasMoreTokens()) {
            if (count == 0) {
                month = st.nextToken();
                count++;
            } else if (count == 1) {
                date = st.nextToken();
                date = String.format("%2s", date).replace(' ', '0'); //Add zero before the string , if its not 2 digit
            }
        }
        System.out.println("Formatted Date is :- "
                + month.concat(" ").concat(date));