4

我正在尝试编写一个在字符串开头查找时间的正则表达式。我想删除字符串的那部分,所以我使用了 regioEnd 函数,但它将 regioend 设置为行尾。

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));

我在这里做错了什么?

4

3 回答 3

4

看起来您只想使用end()而不是regionEnd(). 该end()方法返回超过正则表达式实际匹配的任何结尾的第一个字符的索引。该regionEnd()方法返回匹配器搜索匹配的区域的末尾(这是您可以设置的)。

于 2013-09-01T10:42:20.363 回答
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!"
于 2013-09-02T14:06:42.193 回答
1
String line = "4:12testline to test the matcher!";
line = line.replaceFirst("\\d{1,2}:\\d{1,2}", "");
System.out.println(line);

输出:测试匹配器的测试线!

于 2013-09-02T13:57:34.780 回答