Is there a way for me to format a string based on a regEx pattern. That is can I have a string and apply that pattern. A perfect example would be a phone number or credit card. For instance if I had this function:
public String formatNumber(String input, String patter) {
// What to do...
}
I would like to describe the pattern in a single string rather than do multiple string operations to get the input into the desired format.
Not that the input might not be the entire input but only part of the input and it still needs formatted.
EXAMPLE:
-------
Pattern = "\(\d{3}\) \d{3}-\d{4}"
123456 => (123) 456
1234567 => (123) 456-7
1234567890 => (123) 456-7890
12 => (12
Ok, how about this solution:
Giving credit to @Code Jockey in this post, you could use this regex to match and format valid phone numbers.
There are many variations to this regex and it is very thorough yet flexible. See the example link. Very clever.
Regex:
^\D*1?\D*([2-9])\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d).*$
Replace:
($1$2$3) $4$5$6-$7$8$9$10
Example:
http://regex101.com/r/wM0nU5
Then if match is false, (not a valid phone number), as in your example:
123456
1234567
1234567890
12
You would use another regex, to match and format the invalids - such as:
(.{1,3})(.{1,3})(.{1,3})
Replace:
($1) $2-$3
Example:
http://regex101.com/r/wY3kP2
Personal note: I don't know why you would want to match and format a non-valid phone number. personally I would use the first regex to format valid numbers and then on false matches, request the user to input a valid number. However, I do understand that, with not knowing the exact situation or application, there may be the need or exception somehow to format an invalid phone number.
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