Look for a phone number in a string

2019-08-11 05:10发布

问题:

I have problem with finding phone number in string.

I have function:

   public void getPhoneNumber()
    {
        Pattern intsOnly = Pattern.compile("\\d+");
        Matcher makeMatch = intsOnly.matcher(number);
        makeMatch.find();
        String result = makeMatch.group();
        Log.i("Pattern", result);       
    }

But I have bad result.

My string:

String number = "String string s. s. str. 23-232 12 23 adsdsa"

回答1:

Is your number always in the format 23-232 12 23?. If so you can try the below.

Try the below

    String s="String  string s. s. str. 23-232 12 23 adsdsa";
    Pattern p = Pattern.compile("[0-9]{2}[-][0-9]{3}[ ][0-9]{2}[ ][0-9]{2} ");
    // match 2 numbers followed by -,
    // match 3 numbers followed by space.
    // match 2 numbers followed by space.
    // match 2 numbers followed by space. 
    Matcher m = p.matcher(s); 
    if(m.find()) {
    System.out.println("............"+m.group(0));
    }

Edit:

    Pattern p = Pattern.compile("(\\([0-9]{2}\\)|[0-9]{2})[ ][0-9]{3}[ ][0-9]{2,2}[ ][0-9]{2} ");

Use a or operator match (23) or 23

You can also remove the rounded brackets by using the replace method

String s="String  string s. s. str. (23) 232 32 34  11111adsds0000000000000000a0";
String r = s.replace("(","");  
String r2= r.replace(")", "");
System.out.println(r2);
//String  string s. s. str. 23 232 32 34  11111adsds0000000000000000a0


回答2:

Try using regex, similiar question here: Link

String value = string.replaceAll("[^0-9]","");


回答3:

I wrote this:

This solved my problem :)

public String getPhoneNumber()
    {
        char[] temp = numer.toCharArray();
        String value="";
        int licz=0;

        for(int i=0;i<temp.length;i++)
        {
            if(licz<9)
            {
                if(Character.toString(temp[i]).matches("[0-9]"))
                {
                    value+=Character.toString(temp[i]);
                    licznik++;
                }
                else if(Character.toString(temp[i]).matches("\u0020|\\-|\\(|\\)"))
                {

                }
                else
                {
                    value="";
                    licz=0;
                }
            }
        }

        if(value.length()!=9) 
        {
            value=null;
        }
        else
        {
            value="tel:"+value.trim();
        }

        return value;
    }