Format a string using regex in Java

前端 未结 6 1375
执笔经年
执笔经年 2020-12-14 11:16

Is there any way I can format a string into a specific pattern using regex or is stringbuilder + substring a faster approach?

For example, say a phone number --> 123

6条回答
  •  清歌不尽
    2020-12-14 11:48

    StringBuilder with substring will be faster, but not always the simplest/best approach. In this case I would just use substring.

    String num = "1234567890";
    String formatted = "(" + num.substring(0,3) + ") "
         + num.substring(3,6) + "-" + num.substring(6); 
    

提交回复
热议问题