6

how do i pull the "16" out for both

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

Here is what i have 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 tested the regex("([0-9]+:[0-9]+)+") at http://regexr.com/ and it correctly highlight the "8:16"

2 Answers2

5

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

See demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

String.indexOf(String str) doesn't take a regex. It takes a String.

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

Or to make it look neater, 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); 
Fazer
  • 89
  • 11
  • You are going around in circles. BTW i do not know the value of the "16" or the "8". only that they have a colon in the middle, and may have more colons around it – Kamin Pallaghy Dec 15 '15 at 00:09
  • If the value is stored in a variable you can do the same thing, except you would do this: Line.indexOf(String.valueOf(value)); How exactly am I going in circles? – Fazer Dec 15 '15 at 00:14
  • because if we know what `value` is then we can just do `V = value` – Kamin Pallaghy Dec 15 '15 at 00:20
  • Fair enough, so you want find the string immediately after :? – Fazer Dec 15 '15 at 01:30
  • 1,2,3 - but it may be the 2nd ":" of 2 or 5th of 8, IDK, but it will have 1-3 digits before and after it. – Kamin Pallaghy Dec 17 '15 at 10:54
  • If the answer above worked for you then, I'm not going to spend any resources trying to figure this out. If it didn't, let me know I'll see what I can come up with. – Fazer Dec 17 '15 at 11:08