2015-11-03 82 views
0

無法使用正則表達式來驗證電話號碼。我只想讓數字和連字符,但到目前爲止,我一直試圖讓數字工作。不幸的是,儘管在瀏覽Google和Stack Overflow之後發生了不同的變化,但正則表達式仍然被認爲是錯誤的。理想情況下,字符串(如8889990000888-999-3333)都應評估爲真。任何幫助表示讚賞!對於正則表達式使用正則表達式在Android中驗證電話號碼

Main類代碼:

boolean correct = PhoneFilter.filterPhone(phone_num); 

if (correct == true) { 
    //create an intent to carry data from main activity to OrderConfirmationActivity 
    Intent intent = new Intent(MainActivity.this, OrderConfirmationActivity.class); 

    //pack pizza order data into intent 
    intent.putExtra("nameSelected", nameEditText.getText().toString()); 
    intent.putExtra("aVariable", type); 
    intent.putExtra("mtSelected", mt); 
    intent.putExtra("otSelected", ot); 
    intent.putExtra("ptSelected", pt); 
    intent.putExtra("dateSelected", Date); 

    //start the OrderConfirmationActivity 
    startActivity(intent); 


} 
     //alert user if phone number entered incorrectly 
else if (correct == false) { 
    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); 
    alertDialog.setTitle("Alert"); 
    alertDialog.setMessage("Please enter a phone number in either 000-0000-000 format or 0000000000 format"); 
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 
       } 
      }); 
    alertDialog.show(); 
} 

filterPhone的代碼是:

public class PhoneFilter { 

    public static boolean filterPhone(String phone_text) { 
     boolean correct; 

     if ((phone_text.length() <= 12) && (phone_text.matches("[0-9]+"))) 
      correct = true; 
     else 
      correct = false; 

     System.out.println("correct =" + correct); 
     return correct; 

     //InputFilter lengthFilter = new InputFilter.LengthFilter(12); 
    } 
} 
+0

這可能是值得一讀:http://howtodoinjava.com/2014/11/12/java-正則表達式驗證國際電話號碼/ –

+0

原來,正則表達式不是問題,或者至少只是問題的一部分,顯然我已經忘記在將editText內容分配給字符串時忘記添加'.getText()'變量。 – Matt

回答

1

嘗試切換

phone_text.matches("[0-9]+") 

phone_text.matches("^[0-9-]+$") 

我把一個快速測試嘗試一下:

public static void main(String[] args) { 
    //Sysout for example only 
    System.out.println(filterPhone("8889990000")); 
    System.out.println(filterPhone("888-999-3333")); 
    System.out.println(filterPhone("888B999A3333")); 
    System.out.println(filterPhone("")); 
} 

public static boolean filterPhone(String phone_text) { 
    boolean correct; 

    if ((phone_text.length() <= 12) && (phone_text.matches("^[0-9-]+$"))) 
     correct = true; 
    else 
     correct = false; 

    System.out.println("correct =" + correct); 
    return correct; 

    // InputFilter lengthFilter = new InputFilter.LengthFilter(12); 
} 

產地:

correct =true 
true 
correct =true 
true 
correct =false 
false 
correct =false 
+0

我得到的輸出相同,但是當我嘗試使用edittext中的字符串運行它時,它仍然評估爲false。我會繼續研究它,也許我有一個語法錯誤的地方... – Matt

+0

啊,解決了這個問題,當將editText的內容分配給一個字符串時,需要'.getText()'。感謝您幫助我找出如何正確使用正則表達式! – Matt

+0

沒問題!樂於幫助。 –

相關問題