Split string using Regex and indexOf

I have a simple string Ex. 1.0.0.2

and I want to split and get only part of the line: output: 1.0.0

Basically I want to delete all text after including the third one .

. I tried to use the function split()

by counting the records .

and, if greater than 2, we get the third point indexOf()

and substring()

. Is there an easier or faster way to achieve this? Perhaps using regEx ?

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

+3


source to share


3 answers


If you don't know for sure that there will be exactly three dots - so you can't use lastIndexOf()

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

      

+4


source


It is easy and quick 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("."));

      

While you can achieve the same result with a regex, I wouldn't bother, it was much more verbose, harder to understand (it takes at least a while), and pretty fast for resonant size String

.



change

If you don't know how many points of yours String

you'll need a more complex approach, in which case a regex will do fine, ruakh's + answer does the trick pretty well.

If you prefer more readability (readability depends on your confidence in the regex, of course), you can create a helper method that takes into account the number of occurrences of a character in a string and use that to decide whether to slice it or not.

+3


source


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

      

+1


source







All Articles