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.
You don't need to apply regex,you can just filter out the input.

I have created a sample app , I hope it will be helpful !!

**MainActivity.java**

```
package com.mehuljoisar.d_asyoutypeformatter;

import android.os.Bundle;
import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;

public class MainActivity extends Activity {

    private EditText etCellNumber;

    private InputFilter mCellNumFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            Log.d("dstart", ""+dstart);
            if (source.length() > 0) {

                if (!Character.isDigit(source.charAt(0)))
                    return "";
                else {
                    if (dstart == 0) {
                        return "(" + source;
                    }
                    else if (dstart == 3) {
                        return source + ") ";
                    } 
                    else if (dstart == 9)
                        return "-" + source;
                    else if (dstart >= 14)
                        return "";
                }

            } else {

            }

            return null;

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etCellNumber = (EditText)findViewById(R.id.etCellNumber);
        etCellNumber.setFilters(new InputFilter[] { mCellNumFilter });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

```

**activity\_main.xml**

```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/etCellNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:hint="enter cell number" />

```

**Screenshots :**

![enter image description here](https://i.stack.imgur.com/Q3gH3.png)
![enter image description here](https://i.stack.imgur.com/BXMrR.png)
![enter image description here](https://i.stack.imgur.com/S9a9S.png)
![enter image description here](https://i.stack.imgur.com/SVV9G.png)