2013-08-02 15 views
5

數目的字符結束我試圖檢查一個字符串的起始和使用正則表達式

String string = "123456";  
if(string.startsWith("[0-9]") && string.endsWith("[0-9]")){ 
         //code 
        } 

而且如果條款不會被調用。

+5

是什麼讓你相信這是一個正則表達式的論點? –

+0

變量名稱在哪裏? –

+1

這只是我還是在這個帖子中沒有問題? – Akunosh

回答

16

不要使用正則表達式:

Character.isDigit(string.charAt(0)) && 
           Character.isDigit(string.charAt(string.length()-1)) 

(見Character.isDigit()

+1

我認爲這是更快的方式。 –

+0

我同意,不需要正則表達式。 – dic19

+0

@MattSmith你確定它來自這條線嗎?沒有這種情況導致'IllegalStateException'。嘗試檢查周圍的代碼。 – arshajii

9

方法startsWith()endsWith()String只接受字符串,而不是正則表達式。

+0

非常真實,但就目前而言,這是比評論更多的評論。你會如何建議他們「...... [檢查]字符串是否以數字字符開頭和結尾。」? – Leigh

4

您可以使用:

String string = "123test123"; 
if(string.matches("\\d.*\\d")) 
{ 
    // ... 
} 
+0

工作沒有脫字符號和美元... – sashok724

+1

@ProgramFOX你實際上不需要與'matches()'的錨。 – arshajii

4

您可以使用matches方法上String正是如此:

public static void main(String[] args) throws Exception { 
    System.out.println("123456".matches("^\\d.*?\\d$")); 
    System.out.println("123456A".matches("^\\d.*?\\d$")); 
    System.out.println("A123456".matches("^\\d.*?\\d$")); 
    System.out.println("A123456A".matches("^\\d.*?\\d$")); 
} 

輸出:

true 
false 
false 
false 
0

請遵循代碼段。

String variableString = "012testString"; 
Character.isDigit(string.charAt(0)) && variableString.Any(c => char.IsUpper(c)); 
相關問題