3

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
eltabo
  • 3,749
  • 1
  • 21
  • 33
jjNford
  • 5,170
  • 7
  • 40
  • 64

3 Answers3

1

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.

Community
  • 1
  • 1
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22
0

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

Jijo
  • 611
  • 5
  • 18
0

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

Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57
  • does it work for numbers with a `1`, such as 1(800) 234-3345? just curious. loos like a cool app. :) – Bryan Elliott Jan 18 '14 at 07:04
  • 1
    I think that this is exactly what jjNford was trying to avoid – Mihai Soloi Jan 18 '14 at 07: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 '14 at 07:07
  • @MehulJoisar - yes, that's true, I agree it is a great piece of code. :) – Bryan Elliott Jan 18 '14 at 07:11
  • @MElliott: then why downvote? anyways, you can upvote if you think so. ;-) – Mehul Joisar Jan 18 '14 at 07:23
  • I dont know why the down vote, maybe because the OP was specifically requesting a regex solution who knows,.. people have their own reasons. I told you I admired your app and was good code indicating that I was not your downvoter. – Bryan Elliott Jan 18 '14 at 07:34
  • This code will not work if you delete some numbers and then re input or delete and re input country code. – 3akat Feb 27 '16 at 07:43