简体   繁体   中英

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, ie 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

You can use:

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

RegEx Demo

也许不是最好的解决方案,但是它可以工作:

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

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