How to substring a string to the second dot (.) in Java?
Solution 1
Matcher m = Pattern.compile("^(.*?[.].*?)[.].*")
.matcher("codes.FIFA.buf.OT.1207.2206.idu");
if (m.matches()) {
return m.group(1);
}
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.
Comments
-
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, likecodes.FIFA
.How to substring just until the second dot?
-
Keppil almost 12 yearsYou should use
input.substring(0, dot2)
, otherwise you getcodes.FIF
. -
guido almost 12 yearsyou 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 almost 12 years@guido: I did specify this in my answer.
-
V Joe over 7 yearsWhat would be the code, if i want only "buf" in return from this string?