Skip to content

Instantly share code, notes, and snippets.

@ivamluz
Last active August 29, 2015 14:03
Show Gist options
  • Save ivamluz/fd31289cf64ce1a10790 to your computer and use it in GitHub Desktop.
Save ivamluz/fd31289cf64ce1a10790 to your computer and use it in GitHub Desktop.
Sample Java code formatting a Brazilian phone number using regex along with String.replaceAll()
class PhoneNumberFormat {
public static void main (String[] args) {
System.out.println("21436587".replaceAll("^([0-9]{4,5})[^0-9]*([0-9]{4})$", "$1-$2")); // outputs "2143-6587"
System.out.println("2143-6587".replaceAll("^([0-9]{4,5})[^0-9]*([0-9]{4})$", "$1-$2")); // outputs "2143-6587"
System.out.println("921436587".replaceAll("^([0-9]{4,5})[^0-9]*([0-9]{4})$", "$1-$2")); // outputs "92143-6587"
System.out.println("92143-6587".replaceAll("^([0-9]{4,5})[^0-9]*([0-9]{4})$", "$1-$2")); // outputs "92143-6587"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment