如何在 Java 中将字符串子串到第二个点 (.)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11579605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to substring a string to the second dot (.) in Java?
提问by itro
I have a String which has many segments separated by a dot (.
) like this:
我有一个字符串,它有许多由点 ( .
)分隔的段,如下所示:
codes.FIFA.buf.OT.1207.2206.idu
代码.FIFA.buf.OT.1207.2206.idu
I want to get a substring only until second dot, like codes.FIFA
.
我只想在第二个点之前获得一个子字符串,例如codes.FIFA
.
How to substring just until the second dot?
如何子串直到第二个点?
采纳答案by guido
Matcher m = Pattern.compile("^(.*?[.].*?)[.].*")
.matcher("codes.FIFA.buf.OT.1207.2206.idu");
if (m.matches()) {
return m.group(1);
}
回答by Aleks G
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.
当然,如果找不到点,您可能希望在其中添加错误检查。
回答by Logard
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.
变量 firstTwoSubstrings 将包含第二个“.”之前的所有内容。请注意,如果少于两个“.”,这将导致异常。在你的字符串中。
Hope this helps!
希望这可以帮助!
回答by Keppil
This seems like the easiest solution:
这似乎是最简单的解决方案:
String[] split = "codes.FIFA.buf.OT.1207.2206.idu".split("\.");
System.out.println(split[0] + "." + split[1]);
回答by Thilo
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.
这可能需要一些错误检查,如果它可以少于两个点,或者以一个点开头等。