如何从字符串中提取数字并获取整数数组? [英] How to extract numbers from a string and get an array of ints?
本文介绍了如何从字符串中提取数字并获取整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串变量(基本上是一个带有未指定数字数量的英文句子),我想将所有数字提取到一个整数数组中.我想知道是否有使用正则表达式的快速解决方案?
I have a String variable (basically an English sentence with an unspecified number of numbers) and I'd like to extract all the numbers into an array of integers. I was wondering whether there was a quick solution with regular expressions?
我使用了 Sean 的解决方案并稍作更改:
I used Sean's solution and changed it slightly:
LinkedList<String> numbers = new LinkedList<String>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
numbers.add(m.group());
}
推荐答案
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... 打印 -2
和 12
.
... prints -2
and 12
.
-?匹配前导负号 - 可选.\d 匹配一个数字,但我们需要在 Java 字符串中将 \
写为 \\
.所以,\d+ 匹配 1 个或多个数字.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \
as \\
in a Java String though. So, \d+ matches 1 or more digits.
这篇关于如何从字符串中提取数字并获取整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文