Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a string using regex in Java

Tags:

java

string

regex

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 ???

like image 578
Vrushank Avatar asked Nov 19 '11 19:11

Vrushank


1 Answers

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

like image 56
Alan Moore Avatar answered Oct 05 '22 10:10

Alan Moore