2011-11-23 67 views
3

我正在一些套接字編程的東西,並試圖匹配一些字符串。格式如下:我應該在這裏使用什麼樣的正則表達式?

1.) Some text 

其中一個代表任意數字,一些文本指的是任何東西(包括字母,數字,引號等)。

我嘗試使用[0-9]*\\.\\).*但它不會返回匹配。我做錯了什麼,如何解決?

編輯 按照要求,這裏是我的代碼:

/** Parses data returned by the server */ 
public void getSocketData(String data) { 
    String[] lines = data.split("\\r?\\n"); 
    this.fileHosts = new String[lines.length]; 
    Pattern p = Pattern.compile("[0-9]*\\.\\).*"); 
    for (int i = 0; i < lines.length; i++) { 
     String line = lines[i]; 
     if (p.matcher(line).matches()) { 
      //The format is: 1.) "b.jpg" from "192.168.1.101:40000" 
      String[] info = line.split("\""); 
      this.fileHosts[i] = info[3]; //this should now contain <addr:port> 
      System.out.println("Adding " + fileHosts[i] + " to fileHosts"); 
     } 
     else { 
      System.out.println("No Match!"); 
     } 
    } 
}//getSocketData 
+0

您可以發佈您的Java代碼,使用Ø你的正則表達式?如果這不是因爲反斜槓不匹配,那可能是錯誤的方法調用或其他。 – BoltClock

+0

@BoltClock,當然。我已經修改它來添加代碼。 – Phil

+0

+1用於顯示您嘗試的內容。 – FailedDev

回答

2

這個工作對我來說:

public static void main(String args[]) { 
    String s = "1.) Some text"; 

    System.out.println(s.replaceFirst("^[0-9]+\\.\\).*$","matched")); 
} 

輸出:

matched 

編輯:同樣的結果與如下:

String s = "1.) \"b.jpg\" from \"192.168.1.101:40000\""; 

也就是說在你的代碼中的註釋的例子

EDIT2:我也嘗試你的代碼:

 String s = "1.) \"b.jpg\" from \"192.168.1.101:40000\""; 
     Pattern p = Pattern.compile("^[0-9]+\\.\\).*$"); // works also if you use * instead of + 
     if (p.matcher(s).matches()) { 
      System.out.println("match"); 
     } 
     else { 
      System.out.println("No Match!"); 
     } 

結果是

match 

嘗試使用這個正則表達式: ^[0-9]+\\.\\).*$

+0

感謝您的幫助,瞭解這一點。你徹底的幫助讓你接受了!事實證明,我們的兩個正則表達式都有效。由於我從我的某個套接字獲取數據,因此在我的字符串中有多餘的*不可見*字符,導致它們不匹配。將我的支票更改爲'if(p.matcher(line.trim())。matches())'修復了一切。 – Phil

+0

重要的是我們做到了;) –

相關問題