开发者

splitting a string based on some rules

I have a number in format

10.10.09.09.00

Now i want to find the first three places:

String getformattedString(Strring st开发者_如何学Gor){
  //impl
  return newStr;
}

eg 10.10.09. How can i do it?


Don't have to use a regex, this would work too:

String[] fields = str.split("\\.");

return fields[0] + "." + fields[1] + "." + fields[2] + ".";


Pattern regex = Pattern.compile("^(?:\\d+\\.){3}");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
   // matched text: regexMatcher.group()
}


Here's a one-line solution:

public static String getFormattedString(String str) {
    return str.replaceAll("(^(\\d\\d\\.){3}).*", "$1");
}

Here's the test code:

public static void main(String[] args) {
    System.out.println(getFormattedString("10.10.09.09.00"));
}

Output:

10.10.09.


Regular expressions sounds like what you are after.


Try like this too:

return str.Substring(0, str.LastIndexOf(".", str.LastIndexOf(".") - 1) + 1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜