How to infer a phrase from a string

how i pulled out "16" for both

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

Here is what I tried

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

And here is the error I get

 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) 

I checked the regex ("([0-9] +: [0-9] +) +") at http://regexr.com/ and it correctly highlighted "8:16"

+6
source share
2 answers

You need to put the capture group on the second [0-9]+ (or equivalent, \d+ ) and use 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"); 

Watch the demo

+5
source

String.indexOf (String str) does not accept a regular expression. A string is required.

You can simply do this:

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

To make it look neat, you can replace this line:

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

with:

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

All Articles