我有一个字符串变量(基本上是一个包含未指定数字的英语句子),我想将所有数字提取到一个整数数组中。我想知道是否有正则表达式的快速解决方案?
我使用了Sean的解决方案,并对其进行了细微的修改:
LinkedList<String> numbers = new LinkedList<String>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
numbers.add(m.group());
}
发布于 2010-03-03 06:39:04
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
。
-?匹配前导负号--可选。\d匹配一个数字,但是我们需要在Java String中将\
写成\\
。因此,\d+匹配一个或多个数字。
发布于 2010-03-03 06:39:56
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
int n = Integer.parseInt(m.group());
// append n to list
}
// convert list to array, etc
您实际上可以将0-9替换为\d,但这涉及到双反斜杠转义,这会使其更难阅读。
发布于 2012-02-10 07:12:01
StringBuffer sBuffer = new StringBuffer();
Pattern p = Pattern.compile("[0-9]+.[0-9]*|[0-9]*.[0-9]+|[0-9]+");
Matcher m = p.matcher(str);
while (m.find()) {
sBuffer.append(m.group());
}
return sBuffer.toString();
这是为了提取保留小数的数字。
https://stackoverflow.com/questions/2367381
复制相似问题