Search code examples
androidstringreplacephone-number

Look for a phone number in a string


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"

Solution

  • 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;
        }