2012-07-20 49 views

回答

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

http://ideone.com/N6m8a

+0

如果我只想從該字符串返回「buf」,那麼代碼是什麼? – 2016-11-24 11:18:20

3

這似乎是最簡單的解決方案:

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

只要找到第一個點,然後從那裏第二個:

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); 

當然,你可能要添加在裏面的錯誤檢查,如果沒有找到點。

+0

你應該使用'input.substring(0,DOT2)',否則你'codes.FIF'。 – Keppil 2012-07-20 12:50:29

+0

好點!謝謝,我更新了答案。 – 2012-07-20 12:51:40

+0

你應該添加一些檢查至少有兩個點的存在,否則你會從indexOf得到-1,並且子字符串會拋出非法索引 – 2012-07-20 12:57:21

2

我只希望它再分爲三個部分,並加入了前兩個條件:

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

這可能需要一些錯誤檢查,如果它可以有不到兩個點,或以點等啓動

4

像這樣的事情會做的伎倆:

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

變量firstTwoSubstrings將包含前一秒一切「」請注意,如果少於兩個,將導致異常。「在你的字符串中。

希望這會有所幫助!

相關問題