Harry
Harry

Reputation: 782

Removing everything after a character, including that character

So I have a bunch of Strings that I want to parse into floats. Some of these strings have multiple decimal points, i.e. 100.2.3. I need to simplify this string down to only have 1 decimal point and truncate everything (including the decimal point) after it the second occurrence of the decimal. So, for example, 100.2.3 would simplify to 100.2

Also, there might be more decimals than just two. So, 100.2.3.4.3.4.2 needs to be simplified to 100.2 as well

Is there an easy way to get this done? Thanks

Upvotes: 2

Views: 181

Answers (2)

anubhava
anubhava

Reputation: 785156

You can use:

str = str.replaceFirst("^([^.]+\\.[^.]+)(.+)$", "$1");

RegEx Demo

Upvotes: 4

eric.m
eric.m

Reputation: 1612

Maybe not the best solution, but it works:

String newString = string.split("\\.")[0] + "." + string.split("\\.")[1].split("\\.")[0];

Upvotes: 0

Related Questions