如何从一个字符串中拉出短语

时间:2015-12-14 23:42:04

标签: java regex

我如何拉动" 16"

  • Bar Foo Bar:Foo8:16 Foo Bar Bar foo barz
  • 8:16 Foo Bar Bar foo barz

这是我试过的

String V,Line ="Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
V = Line.substring(Line.indexOf("([0-9]+:[0-9]+)+")+1);
V = V.substring(V.indexOf(":")+1, V.indexOf(" "));
System.out.println(V);

这是我得到的错误

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
    at java.lang.String.substring(String.java:1955)  
    at Indexing.Index(Indexing.java:94)  
    at Indexing.main(Indexing.java:24)

我在http://regexr.com/测试了正则表达式("([0-9] +:[0-9] +)+")并正确地突出显示" 8: 16"

2 个答案:

答案 0 :(得分:5)

您需要将捕获组放在第二个[0-9]+(或等效的\d+)并使用 Matcher#find()

String value1 = "Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
String pattern1 = "\\d+:(\\d+)"; // <= The first group is the \d+ in round brackets
Pattern ptrn = Pattern.compile(pattern1);
Matcher matcher = ptrn.matcher(value1);
if (matcher.find())
    System.out.println(matcher.group(1)); // <= Print the value captured by the first group
else
    System.out.println("false");

请参阅demo

答案 1 :(得分:0)

String.indexOf(String str)不接受正则表达式。它需要一个字符串。

你可以这样做:

String V, Line = "Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
V = Line.substring(Line.indexOf("16"), Line.indexOf("16") + 2);
System.out.println(V);

或者为了使它看起来更整洁,你可以替换这一行:

V = Line.substring(Line.indexOf("16"), Line.indexOf("16") + 2);

使用:

int index = Line.indexOf("16");
V = Line.substring(index, index + 2);