How to substring a string to the second dot (.) in Java?

17,111

Solution 1

 Matcher m = Pattern.compile("^(.*?[.].*?)[.].*")
                    .matcher("codes.FIFA.buf.OT.1207.2206.idu");
 if (m.matches()) {
      return m.group(1);
 }

http://ideone.com/N6m8a

Solution 2

Just find the first dot, then from there the second one:

String input = "codes.FIFA.buf.OT.1207.2206.idu";
int dot1 = input.indexOf(".");
int dot2 = input.indexOf(".", dot1 + 1);
String substr = input.substring(0, dot2);

Of course, you may want to add error checking in there, if dots are not found.

Solution 3

Something like this will do the trick:

String[] yourArray = yourDotString.split(".");
String firstTwoSubstrings = yourArray[0] + "." + yourArray[1];

The variable firstTwoSubstrings will contain everything before the second ".". Beware that this will cause an exception if there are less than two "." in your string.

Hope this helps!

Solution 4

This seems like the easiest solution:

String[] split = "codes.FIFA.buf.OT.1207.2206.idu".split("\\.");
System.out.println(split[0] + "." + split[1]);

Solution 5

I'd just split it into three parts and join the first two again:

String[] parts = string.split("\\.", 3);
String front = parts[0]+"."+parts[1];
String back = parts[2];

This may need some error checking if it can have less than two dots, or start with a dot, etc.

Share:
17,111
itro
Author by

itro

I do software .

Updated on June 13, 2022

Comments

  • itro
    itro almost 2 years

    I have a String which has many segments separated by a dot (.) like this:

    codes.FIFA.buf.OT.1207.2206.idu


    I want to get a substring only until second dot, like codes.FIFA.

    How to substring just until the second dot?

  • Keppil
    Keppil almost 12 years
    You should use input.substring(0, dot2), otherwise you get codes.FIF.
  • guido
    guido almost 12 years
    you should add some check against the existence of at least two dots as well, or you will get -1 out from indexOf and substring will throw illegalargument
  • Aleks G
    Aleks G almost 12 years
    @guido: I did specify this in my answer.
  • V Joe
    V Joe over 7 years
    What would be the code, if i want only "buf" in return from this string?