我如何为两者拉出"16"
这是我尝试过的
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);
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
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)
Run Code Online (Sandbox Code Playgroud)
我在http://regexr.com/上测试了正则表达式("([0-9] +:[0-9] +)+"),它正确地突出了"8:16"
您需要将捕获组放在第二个[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");
Run Code Online (Sandbox Code Playgroud)
见演示
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |