我想从一个句子中得到整数、浮点数或双值。举个例子--“约翰有20个球,其中4个是红色的,5个是绿色的。”这将是我的投入。我想从那条线得到号码20,4,5。如何在java中做到这一点。请告诉我如果我能用扫描仪做那件事。我不想用缓冲区阅读器。
发布于 2022-02-12 11:11:25
使用regex匹配数字并从输入中收集它们:
List<String> numbers = Pattern.compile("\\d+(\\.\\d+)?")
.matcher(sentence)
.results() // stream the MatchResults
.map(MatchResult::group) // get the entire match
.collect(Collectors.toList()); // collect as a List见现场演示。
这适用于整数和小数。
https://stackoverflow.com/questions/71090893
复制相似问题