Format a string using regex in Java

前端 未结 6 1371
执笔经年
执笔经年 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:37

    The same technique works in Java; you just have to adjust the to Java syntax and API:

    s = s.replaceFirst("(\\d{3})(\\d{3})(\\d{4})", "($1) $2-$3");
    

    I don't understand why you're asking about the faster approach, though. Have you tried something like this and experienced performance problems? You can almost certainly do this more efficiently with a StringBuilder, but in practical terms it's almost certainly not worth the effort.

    Or were you talking about the time it would take to learn how to accomplish this with a regex relative to hand-coding it with a StringBuilder? That's kind of a moot point now, though. :D

提交回复
热议问题