Java 如何从字符串中提取数字并获取整数数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2367381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract numbers from a string and get an array of ints?
提问by John Manak
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?
我有一个字符串变量(基本上是一个带有未指定数字数量的英文句子),我想将所有数字提取到一个整数数组中。我想知道是否有正则表达式的快速解决方案?
I used Sean's solution and changed it slightly:
我使用了 Sean 的解决方案并稍作更改:
LinkedList<String> numbers = new LinkedList<String>();
Pattern p = Pattern.compile("\d+");
Matcher m = p.matcher(line);
while (m.find()) {
numbers.add(m.group());
}
采纳答案by Sean Owen
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());
}
... prints -2
and 12
.
... 打印-2
和12
。
-? 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.
-?匹配前导负号 - 可选。\d 匹配一个数字,但我们需要\
像\\
在 Java 字符串中那样编写。所以,\d+ 匹配 1 个或多个数字。
回答by Andrey
for rational numbers use this one: (([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))
对于有理数使用这个: (([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))
回答by sidereal
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
You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.
您实际上可以用 \d 替换 [0-9],但这涉及双反斜杠转义,这使得阅读变得更加困难。
回答by Kannan
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();
This is for extracting numbers retaining the decimal
这是用于提取保留小数的数字
回答by The_Fresher
I would suggest to check the ASCII values to extract numbers from a String Suppose you have an input String as myname12345and if you want to just extract the numbers 12345you can do so by first converting the String to Character Arraythen use the following pseudocode
我建议检查 ASCII 值以从字符串中提取数字假设您有一个输入字符串作为 myname12345,如果您只想提取数字 12345,您可以先将字符串转换为字符数组,然后使用以下伪代码
for(int i=0; i < CharacterArray.length; i++)
{
if( a[i] >=48 && a[i] <= 58)
System.out.print(a[i]);
}
once the numbers are extracted append them to an array
提取数字后,将它们附加到数组中
Hope this helps
希望这可以帮助
回答by Maxim Shoustin
What about to use replaceAll
java.lang.String method:
使用replaceAll
java.lang.String 方法怎么样:
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
输出:
[-1, -2, 455, 0, 4]
Description
描述
[^-?0-9]+
[
and]
delimites a set of characters to be single matched, i.e., only one time in any order^
Special identifier used in the beginning of the set, used to indicate to match all characters notpresent in the delimited set, instead of all characters present in the set.+
Between one and unlimited times, as many times as possible, giving back as needed-?
One of the characters “-” and “?”0-9
A character in the range between “0” and “9”
[
并将]
一组字符分隔为单个匹配,即,只能按任何顺序匹配一次^
用于集合开头的特殊标识符,用于指示匹配所有不存在于定界集合中的字符,而不是存在于集合中的所有字符。+
在一次和无限次之间,尽可能多次,根据需要回馈-?
字符“-”和“?”之一0-9
介于“0”和“9”之间的字符
回答by Mugoma J. Okomba
The accepted answer detects digits but does not detect formated numbers, e.g. 2,000, nor decimals, e.g. 4.8. For such use -?\\d+(,\\d+)*?\\.?\\d+?
:
接受的答案检测数字但不检测格式化数字,例如 2,000,也不检测小数,例如 4.8。对于这种用途-?\\d+(,\\d+)*?\\.?\\d+?
:
Pattern p = Pattern.compile("-?\d+(,\d+)*?\.?\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("Government has distributed 4.8 million textbooks to 2,000 schools");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);
Output:
[4.8, 2,000]
输出:
[4.8, 2,000]
回答by Bernhard Barker
Using Java 8, you can do:
使用 Java 8,您可以执行以下操作:
String str = "There 0 are 1 some -2-34 -numbers 567 here 890 .";
int[] ints = Arrays.stream(str.replaceAll("-", " -").split("[^-\d]+"))
.filter(s -> !s.matches("-?"))
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
If you don't have negative numbers, you can get rid of the replaceAll
(and use !s.isEmpty()
in filter
), as that's only to properly split something like 2-34
(this can also be handled purely with regex in split
, but it's fairly complicated).
如果你没有负数,你可以去掉replaceAll
(并使用!s.isEmpty()
in filter
),因为那只是为了正确拆分类似的东西2-34
(这也可以纯粹用正则表达式 in 处理split
,但它相当复杂)。
Arrays.stream
turns our String[]
into a Stream<String>
.
Arrays.stream
将我们的String[]
变成Stream<String>
.
filter
gets rid of the leading and trailing empty strings as well as any -
that isn't part of a number.
filter
去除前导和尾随空字符串以及任何-
不属于数字的字符串。
mapToInt(Integer::parseInt).toArray()
calls parseInt
on each String
to give us an int[]
.
mapToInt(Integer::parseInt).toArray()
呼吁parseInt
每个String
人给我们一个int[]
.
Alternatively, Java 9 has a Matcher.resultsmethod, which should allow for something like:
或者,Java 9 有一个Matcher.results方法,它应该允许以下内容:
Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher("There 0 are 1 some -2-34 -numbers 567 here 890 .");
int[] ints = m.results().map(MatchResults::group).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
As it stands, neither of these is a big improvement over just looping over the results with Pattern
/ Matcher
as shown in the other answers, but it should be simpler if you want to follow this up with more complex operations which are significantly simplified with the use of streams.
既然这样,这些都不是一个很大的进步了刚刚遍历的结果Pattern
/Matcher
如图所示其他的答案,但如果你想用更复杂的操作,这些操作与使用的显著简化跟进它应该是简单流。
回答by user2902302
I found this expression simplest
我发现这个表达最简单
String[] extractednums = msg.split("\\D++");
回答by Swagger 68
Extract all real numbers using this.
使用这个提取所有实数。
public static ArrayList<Double> extractNumbersInOrder(String str){
str+='a';
double[] returnArray = new double[]{};
ArrayList<Double> list = new ArrayList<Double>();
String singleNum="";
Boolean numStarted;
for(char c:str.toCharArray()){
if(isNumber(c)){
singleNum+=c;
} else {
if(!singleNum.equals("")){ //number ended
list.add(Double.valueOf(singleNum));
System.out.println(singleNum);
singleNum="";
}
}
}
return list;
}
public static boolean isNumber(char c){
if(Character.isDigit(c)||c=='-'||c=='+'||c=='.'){
return true;
} else {
return false;
}
}