0

I need to extract a mobile number from a string. I have extracted numbers from string, but failed to get what I need.

Here is the input: a string contains an address and phone number.

String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903"

I need to extract the mobile number, which is 92166-29903.

I use this method to check whether a string contains a mobile number or not:

private Boolean isMobileAvailable(String string)
{
    Boolean ismobile = false;
    if (string.matches("(?i).*M.*"))
    {
        ismobile = true;
    } 
    return ismobile;
}

Used in a code as follows:

String mobilenumber="";

private void getMobileNumber(String sample)
{
    int index = sample.indexOf("M");
    String newString = "";
    newString = sample.substring(index, sample.length());
    mobileNumber = newString.replaceAll("[^0-9]", "");
    edtMobile.setText(mobileNumber.substring(0, 10));
}

Here, instead of mobile number, I am getting 147009211.

How can I identify the mobile number correctly from above string?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Archana
  • 59
  • 8
  • Maybe the regex provided in this post is what you are looking for: http://stackoverflow.com/questions/8634139/phone-validation-regex – Fabian Lang Oct 05 '15 at 08:12
  • Have you at least debug your app? Do you know what is wrong? (hint: `sample.indexOf()` finds the **first** instance of the string... there's another function for finding the **last** one) – Andrew T. Oct 05 '15 at 08:17
  • What types do your result have?such as 92166-29903 you mentioned here. – starkshang Oct 06 '15 at 11:10
  • it can be any mobile number.@FireSun – Archana Oct 06 '15 at 11:59

2 Answers2

0
int index = sample.lastIndexOf("M");
String newString = sample.substring(index+2, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));

If you want the "-" in your result,just delete
mobileNumber = newString.replaceAll("[^0-9]", "");

starkshang
  • 8,228
  • 6
  • 41
  • 52
  • But the problem is the input string is dynamic and the so it couldnt help finding the last index of M.Because some other string can accompany mobile like EMAIL .In case no number stored in mobilenumber variable.How to recognise mobilenumber in such a case.thanks – Archana Oct 06 '15 at 11:04
0

try this code. Method 1:

String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903";
    int value = input.lastIndexOf(":");
    String s = input.substring(value + 1, input.length());
    Log.d("reverseString", "" + s);

Method 2:

  StringBuffer reverseString=new StringBuffer(input);
    StringBuffer s1=reverseString.reverse();
    int firstindex=s1.indexOf(":");
    String finalstring=s1.substring(0, firstindex);
    StringBuffer getexactstring=new StringBuffer(finalstring);

this code will give you exact mobile number that you want.

Amey Bawiskar
  • 361
  • 1
  • 3
  • 17