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 --> 1234567890 as input
And get output as --> (123) 456-7890
I saw it is possible on this article : http://www.4guysfromrolla.com/webtech/031302-1.shtml but the given explanation is in ASP. How do I do it in Java ???
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With