2010-08-30 25 views
4

一些字符串替換字符串我如何可以替換以下字符串中的Java:排除在Java中

Sports videos (From 2002 To 2003) here. 

TO

Sports videos 2002 2003 here. 

我使用的代碼,但它刪除整個字符串即
我得到這個輸出:Sports videos here.

String pattern= "\\((From)(?:\\s*\\d*\\s*)(To)(?:\\s*\\d*\\s*)\\)"; 

String testStr = "Sports videos (From 2002 To 2003) here."; 

String testStrAfterRegex = testStr.replaceFirst(pattern, ""); 

這裏缺少什麼?

感謝

顯示日期格式器不同的字符串

如果上面的字符串有日期格式一樣(\\)或任何其他字符/詞,然後數字,答案是行不通的

我更換原始答案與此模式,它將工作

String pattern= "\\((From)(.*)(To)(.*)\\)"; 

回答

3

更改爲

String pattern= "\\((From)(\\s*\\d*\\s*)(To)(\\s*\\d*\\s*)\\)"; 
    String testStr = "Sports videos (From 2002 To 2003) here."; 
    String testStrAfterRegex = testStr.replaceFirst(pattern, "$2 $4"); 

有兩個問題:

首先

你把(?:)成羣多年。這是用來不記得這些組。

您不使用組標識符,如$ 1,$ 2。 我使用2美元和4美元的第2和第4組固定。


編輯

清潔的解決方案:

String pattern= "\\(From(\\s*\\d*\\s*)To(\\s*\\d*\\s*)\\)"; 
    String testStr = "Sports videos (From 2002 To 2003) here."; 
    String testStrAfterRegex = testStr.replaceFirst(pattern, "$1$2"); 
+0

我在哪裏可以學習組標識符。?另外如果我想用 - (短劃線)替換「TO」。即體育視頻2002-2003在這裏。 – NETQuestion 2010-08-30 02:09:48

+0

我發現自己 String testStrAfterRegex = testStr.replaceFirst(pattern,「$ 2 - $ 4」); – NETQuestion 2010-08-30 02:16:45

+0

@NETQuestion:你好,你可以在這裏瞭解更多http://www.regular-expressions.info/brackets.html – Topera 2010-08-30 02:21:22