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

2019-08-08 15:59发布

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 :/

3条回答
倾城 Initia
2楼-- · 2019-08-08 16:17

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楼-- · 2019-08-08 16:22

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));
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-08-08 16:30

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>
查看更多
登录 后发表回答