简体   繁体   中英

Regular expression number

My target is to format next number 01122222222 to this 011-22-22-22-22 First three numbers of number, dash and all next numbers with dash after second one. Already tried:

private String phoneFormat(String phoneNumber){
    String regex = "\\B(?=(\\d{3})+(?!\\d))";
    String formattedPhone = phoneNumber.replaceAll(regex, Constants.Characters.DASH);
    return formattedPhone;
}

but it produce different result.

A regex will do the trick. Replace sets of 2 digits with "-[digit][digit]" as long as you have 3 digits before those.

public static void main(String[] args) {
    String s = "01122222222";
    System.out.println(s.replaceAll("(?<=\\d{3})(\\d{2})+?", "-$1"));
}

Live Example

O/P :

011-22-22-22-22

PS : This approach should NOT be used in prod environment and has been written solely to please my own stubbornness that this problem can be solved using one regex.

Since at first your question wasn't clear, I had a solution for both Java and Javascript. I'll leave the javascript one in here as well just 'cause :-)

Java 8

First we use substring(0,3) to get the first three numbers. We add - to this, and with the remaining group ( x.substring(3) ), we split them in groups of two, and we join them together with String.join and use - as the concatenating character.

String test = "01122222222";
String res = test.substring(0,3) + "-";
String[] parts = test.substring(3).split("(?=(?:..)*$)");
res += String.join("-",parts);

System.out.println(res);

Live Example


Pre Java 8

From the comments it became clear that you are not using Java 8, so pre-java8 there are various other solutions. You could use a loop like I have done, and add the last part manually. (Alternatively, you could just create the string with each element in the loop, and take the substring again to remove the last - ).

String test = "01122222222";
String res = test.substring(0,3) + "-";
String[] parts = test.substring(3).split("(?=(?:..)*$)");
for(int i = 0; i < parts.length-1; i++){
    res += parts[i]+"-";
}
res+=parts[parts.length-1];
System.out.println(res);

Live Example


Javascript

Using the same logic, you could do this in javascript as well. You can run the snippet to see that the result is actually what you expected.

 var x = "01122222222"; var res = x.substring(0,3) +"-"+ x.substring(3).split(/(?=(?:..)*$)/).join("-"); console.log(res) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM