简体   繁体   中英

Split string using Regex and indexOf

I have a simple string Ex. 1.0.0.2 and I want to split and retrieve only part of the string: output: 1.0.0 basically I want to remove all text after the third . included. I tried with split() function, count the occurrances of . and, if greater than 2, get the indexOf() third point and substring() . Is there an easier or faster method to achieve this? Maybe using regEx ?

Edit: I don't know how many dots there will be.

If you don't know for sure that there will be exactly three dots — so you can't use lastIndexOf() — then here is a regex-based solution:

final Matcher m = Pattern.compile("^[^.]*(?:[.][^.]*){0,2}").matcher(input);
m.find(); // guaranteed to be true for this regex
final String output = m.group(0);

It's simple and fast to do this using only substring and lastIndexOf . I think the code is quite readable:

String str = "1.0.0.1";
String output = str.substring(0, str.lastIndexOf("."));

Although you can achieve the same with a regex, I wouldn't bother, it's a lot more verbose, harder to understand (takes you a while longer at least), and this is quite fast for a resonable sized String .

edit

In case you don't know how many dots your String will have you need a more complex approach, and in that case, a regex would do fine, +ruakh's answer does the trick quite nicely.

If you prefer more readability (readability depends on your confort around regexes, of course), you can create an auxiliary method that counts the number of occurrences of a character in a string, and use that to decide if you should chop it or not.

String input = "1.0.0.2";
String output = input.substring(0, input.lastIndexOf("."));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM