cbll cbll - 1 month ago 7
Java Question

Java: Print specific substring based on characters appearing before, and end if meeting letters after?

I have an input string, let's say it's

111.112.111.0.0 > 111.33.44.55.11 pxs ikf len 3348
, it might also sometimes be input via the stream as
111.112.111.0.0 > 111.33.44.55.11 pxs ikf len 3348 BBBTTT
.

How do I capture the numbers occuring after "len" in the via substring? Using
system.out.println(stringStr.substring(stringStr.lastIndexOf(" ") + 1)
will only print
3348
if it's the last part of the string above, but if BBBTTT appears, it will not work.

How do I print the numbers of a substring specifically after "len" but not including anything but the numbers that follow(might be 0-9999, not more), so not any characters following?

Answer

You can use split method for this.

        String s = "111.112.111.0.0 > 111.33.44.55.11 pxs ikf len 3348 BBBTTT";
    s = s.split("len")[1];
    s = s.replaceAll("\\D+", "");
    System.out.println(s);

or just

s = s.split("len")[1].replaceAll("\\D+", "");