Suppose I have a phone number stored in the string "0991234567".

What kind of manipulations with regular expressions can bring this line to the form "+450 (99) 123 45 67"?

  • Where did the code +45 come from? Is it the same for all phones? Is the city code always (99)? Parsing an arbitrary phone number is not exactly a trivial thing. - LbISS
  • Well, let's say +45 is the country code, and 99 is the operator code. That is, +45 is added to all numbers. The essence of the question is how using regex you can insert the necessary characters in certain places of the string. - Dmitry Pyslar

1 answer 1

If the city and country codes are always the same (taking into account the comments) then regular expressions are not even needed, the combination substring and concat will do everything.

If you really want to do this with regular expressions, then in the simplest case, I would write this:

 string phone = "0991234567"; phone.replaceAll("(\\d)(\\d{2,3})(\\d{3})(\\d{2})(\\d{2})", "+45$1 ($2) $3 $4 $5"); 

Once again, I note that the analysis of an arbitrary number is not done in this way. The number of digits in the city, country code, the number of digits in the number itself may be different.

  • Of course, you can do it without regular expressions, but they were interested in them as an educational example. - Dmitry Pyslar