0

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?

AutoTester999
  • 528
  • 1
  • 6
  • 25
  • What do you mean by "efficient"? – tgdavies Oct 29 '22 at 01:23
  • See https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java/4480774#4480774 – tgdavies Oct 29 '22 at 01:26
  • Just any piece of code that works. I meant shorter rather than efficient. – AutoTester999 Oct 29 '22 at 01:28
  • 2
    Just use `split`. Which is neither time nor space efficient, as it uses a regex and makes copies of parts of the string you con't care about. – tgdavies Oct 29 '22 at 01:32
  • 1
    Your examples all have the part you want to extract in position 9. Is that always going to be the case? Or will it vary? `abcd:e:fghijk:123:trwe` for example? – Old Dog Programmer Oct 29 '22 at 01:46
  • "What is a short way in Java using string functions to extract it?" - The call to a dedicated method. I mean, if the correct abstraction of your requirement is indeed "extract the string between the 3rd colon and the 4th colon", and you want to write fast efficient code, it's gonna be a few lines in said method. – Dreamspace President Oct 29 '22 at 05:12

2 Answers2

2

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
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Teddy Tsai
  • 414
  • 1
  • 13
1

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
WJS
  • 36,363
  • 4
  • 24
  • 39