Home > Net >  Get substring between 3rd colon and 4th colon
Get substring between 3rd colon and 4th colon

Time:10-29

I have strings in the below pattern:

ab:ab:ab:1:ab
ac:ac:ac:2:ac
ad:ad:ad:3:ad

I have to extract the string between the 3rd colon and the 4th colon.

For the above example strings, the results would be "1", "2" and "3".

What is a short way in Java using string functions to extract it?

CodePudding user response:

You can just split by ":" and get the fourth element:

something like:

Stream.of("ab:ab:ab:1:ab", "ac:ac:ac:2:ac", "ad:ad:ad:3:ad")
      .map(s -> s.split(":")[3]).forEach(System.out::println);

Output:

1
2
3

CodePudding user response:

And as an alternative, replace the entire string with the desired item via a capture.

  • (?:.*?:){3} - non capturing group of three reluctant strings followed by a :
  • (.*?) - the capture of the target between 3rd and 4th colon.
  • .*$ - the rest of the string to the end.
  • $1 - the reference to the first (and only) capture group
String[] data = { "ab:ab:ab:1:ab",
 "ac:ac:ac:2:ac",
 "ad:ad:ad:3:ad"};

for (String str : data) {
    System.out.println(str.replaceAll("(?:.*?:){3}(.*?):.*$","$1"));
}

prints

1
2
3
  • Related