Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question
    
Not sure if this helps –  gtgaxiola Jan 18 at 5:26
    
Probably worth looking at the RegEx answer in this question: stackoverflow.com/questions/8196771/… –  Durandal Jan 18 at 5:27
    
Looked at this but no totally following. I'll add addition criteria. –  jjNford Jan 18 at 5:36
    
add an example of input string and required formatted string.so that we can help you with what you really want. –  Mehul Joisar Jan 18 at 5:39
    
why would you want to match and format an incomplete phone number? –  MElliott Jan 18 at 6:03

3 Answers 3

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

share|improve this answer

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.

share|improve this answer

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 enter image description here enter image description here enter image description here

share|improve this answer
    
does it work for numbers with a 1, such as 1(800) 234-3345? just curious. loos like a cool app. :) –  MElliott Jan 18 at 7:04
1  
I think that this is exactly what jjNford was trying to avoid –  Mihai Soloi Jan 18 at 7:06
1  
@MElliott: It won't work like that,so it is perfect piece of code.as I have implemented the filter according to his requirement mentioned "\(\d{3}\) \d{3}-\d{4}". –  Mehul Joisar Jan 18 at 7:07
    
May I know the reason of downvote? –  Mehul Joisar Jan 18 at 7:08
    
@MehulJoisar - yes, that's true, I agree it is a great piece of code. :) –  MElliott Jan 18 at 7:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.