Optionally using String.split (), split the string the last time the separator is filled

I have a line that matches this regular expression: ^.+:[0-9]+(\.[0-9]+)*/[0-9]+$which can be easily visualized as (Text):(Double)/(Int). I need to break this line into three parts. Usually this would be easy, except that it (Text)might contain a colon, so I cannot split into any colon, not the last colon.

.*is greedy, so it already does a pretty neat job, but it won’t work like a regular expression in String.split (), because it will eat mine (Text)as part of the delimiter. Ideally, I would like to have something that returns String [] with three lines. I am 100% right without using String.split () for this.

+5
source share
3 answers

Why don't you just use direct regex?

Pattern p = Pattern.compile("^(.*):([\\d\\.]+)/(\\d+)$");
Matcher m = p.matcher( someString );
if (m.find()) {
  m.group(1); // returns the text before the colon
  m.group(2); // returns the double between the colon and the slash
  m.group(3); // returns the integer after the slash
}

Or similarly. The sample ^(.*):([\d\.]+)/(\d+)$assumes that you really have values ​​in all three positions and allow just a period / full revolution in a double position, so you can customize it according to your specifications.

+3
source

I don't like the regex (just kidding, but I'm not very good at that).

String s = "asdf:1.0/1"
String text = s.substring(0,s.lastIndexOf(":"));
String doub = s.substring(s.lastIndexOf(":")+1,text.indexOf("/"));
String inte = s.substring(text.indexOf("/")+1,s.length());
+5
source

String.split() usually used in simpler scenarios where separator and formatting are more consistent, and when you don’t know how many elements you are going to split.

In your use case, the usual old regular expression is used. You know the formatting of a string, and you know that you want to collect three values. Try the following:

Pattern p = Pattern.compile("(.+):([0-9\\.]+)/([0-9]+)$");
Matcher m = p.matcher(myString);
if (m.find()) {
    String myText = m.group(1);
    String myFloat = m.group(2);
    String myInteger = m.group(3);
}
+1
source

All Articles