Question: 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

```

Answer: 
Ok, how about this solution:

Giving credit to @Code Jockey in [this post](https://stackoverflow.com/questions/8196771/format-a-string-using-regex-in-java), 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.
This is what i can do for you

```
public class HelloWorld{

 public static void main(String []args){
   String input = "1234567890";
   String patter = "(%s) %s-%s";
   HelloWorld hello = new HelloWorld();
   hello.formatNumber(input,patter);
 }
 public String formatNumber(String input, String patter) {
    System.out.println(input);
    System.out.println(patter);
    System.out.println(String.format(patter,input.substring(0,3),input.substring(3,6),input.substring(6,10)));
    return null;
 }
}

```

You can modify it according to your needs