2013-09-01 48 views
4

我想寫一個正則表達式,它在字符串的開頭找到時間。 我想刪除字符串的那部分,所以我使用的是regioEnd函數,但它將該區域的行尾設置爲 。Java的正則表達式區域

Pattern pattern = Pattern.compile("\\d+.\\d+"); 
String line = "4:12testline to test the matcher!"; 
System.out.println(line); 
Matcher matcher = pattern.matcher(line); 
int index = matcher.regionEnd(); 
System.out.println(line.substring(index)); 

我在做什麼錯在這裏?

+1

無需發佈答案的問題的一部分。相反,只是標記正確的答案像[this](http://meta.stackexchange.com/a/5235/186652) – Pshemo

回答

1
String line = "4:12testline to test the matcher!"; 
line = line.replaceFirst("\\d{1,2}:\\d{1,2}", ""); 
System.out.println(line); 

輸出: 測試線測試匹配器!

4

看起來你只想用end()而不是regionEnd()end()方法返回超過正則表達式實際匹配的結尾的第一個字符的索引。 regionEnd()方法返回匹配器搜索匹配區域的結束位置(您可以設置該位置)。

+0

mmh沒有,我只得到 異常在線程「主」java.lang.IllegalStateException:不匹配可用 – ramin

+2

噢,別忘了調用'matcher.find()'來真正尋找你的正則表達式。 –

2

在我看來,你可以簡單地使用.replaceFirst("\\d+:\\d+", "")

String line = "4:12testline to test the matcher!"; 
System.out.println(line.replaceFirst("\\d+:\\d+", "")); 
// prints "testline to test the matcher!"