如何解析字符串以正确获取小数点和带点的单词? [英] How do I parse a String to get the decimal and a word with a dot properly?

查看:141
本文介绍了如何解析字符串以正确获取小数点和带点的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何区分查找小数点的区别,但如果是句点,则同时忽略它?

How do I differentiate the difference in finding a decimal but at the same time ignoring it if it is a period?

例如,假设扫描仪

String s = "2015. 3.50 please";

当我使用函数 scanner.hasNextFloat(),如何忽略嗨。

When I use the function scanner.hasNextFloat(), how do I ignore Hi.?

我只扫描1行。我需要确定一个单词是字符串,整数还是浮点数。我的最终结果应如下所示:

I am only scanning 1 line. I need to identify whether a word is string, integer, or float. My final result should look something like this:

This is a String: 2015.
This is a float: 3.50
This is a String: please

但是在我的条件下,当我使用 scanner.hasNextFloat(); 时,它会将 2015。标识为浮点数。

But in my conditions when I use scanner.hasNextFloat(); it identifies 2015. as a float.

推荐答案

在Java中,您可以使用正则表达式。一个或多个数字,后跟一个文字点,然后是两个数字。

In Java, you might use a regular expression. One or more digits, followed by a literal dot and then two digits. Something like

String s = "Hi. 3.50 please";
Pattern p = Pattern.compile(".*(\\d+\\.\\d{2}).*");
Matcher m = p.matcher(s);
Float amt = null;
if (m.matches()) {
    amt = Float.parseFloat(m.group(1));
}
System.out.printf("Ammount: %.2f%n", amt);

输出为

Ammount: 3.50

这篇关于如何解析字符串以正确获取小数点和带点的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆