1

I am trying to extract phone number in java from the given String i.e. the phone number can be anywhere in the String like [bla bla]TELEPHONE NUMBER[bla bla].Now I want to extract this telephone number in another String.

While using the

 matcher.matches()

it returns me true or false but I am not getting the phone number which it gets extracted.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Amandeep Singh
  • 3,754
  • 8
  • 51
  • 72

3 Answers3

4

To find number in any given format You can use use libphonenumber and findNumbers function.

pixel
  • 24,905
  • 36
  • 149
  • 251
2
Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher m = p.matcher("Testing123Testing");

if (m.find()) {
    System.out.println(m.group(1));
}
Rupok
  • 2,062
  • 16
  • 16
  • 1
    I don't think that 123 is a phone number. Your regex matches single numbers too... – Fred Oct 27 '11 at 07:28
  • 123 is just an example.it will take account 0-9 – Rupok Oct 27 '11 at 07:30
  • 1
    Yeah but he is trying to find phone numbers which is different then just looking for number in a String – Fred Oct 27 '11 at 07:34
  • Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*"); where you can make your desire pattern – Rupok Oct 27 '11 at 07:36
  • I tried this:Matcher matcher = Pattern.compile("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$+").matcher("abc (213) 240-7838"); if(matcher.find()) { System.out.println(matcher.group(1)); },but not working – Amandeep Singh Oct 27 '11 at 07:37
  • Of course... your regex does not match letters... remove `^` and `$` and it should work. `\(?(\\d{3})\)?[- ]?(\\d{3})[- ]?(\\d{4})` – Fred Oct 27 '11 at 07:39
  • Matches following phone numbers: (123)456-7890, 123-456-7890,1234567890, (123)-456-7890 String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; Pattern pattern = Pattern.compile(expression); – Rupok Oct 27 '11 at 07:47
  • Possible duplicate answer: http://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java/237068#237068 – lukastymo Oct 27 '11 at 08:03
  • 1
    Haha, where I live, 123 is indeed a phone number! – Dawood ibn Kareem Dec 13 '13 at 09:01
1

Assuming your regular expression works as it should, you should take a look at this regex tutorial from Sun.

npinti
  • 51,780
  • 5
  • 72
  • 96