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?
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]", "");