Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull phrase out of a string

Tags:

java

regex

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"

like image 630
Kamin Pallaghy Avatar asked Dec 14 '15 23:12

Kamin Pallaghy


Video Answer


1 Answers

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

like image 150
Wiktor Stribiżew Avatar answered Sep 26 '22 14:09

Wiktor Stribiżew