如何从一个字符串中提取号码,并得到int数组? [英] How to extract numbers from a string and get an array of ints?

查看:172
本文介绍了如何从一个字符串中提取号码,并得到int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量(基本上是一个英语句子用数字的数目不详),我想所有的数字提取到一个整数数组。我不知道是否有定期的前pressions一个快速的解决方案?


我用肖恩的解决方案,并改变了它稍微:

 的LinkedList<串GT;数=新的LinkedList<串GT;();模式P = Pattern.compile(\\\\ D +);
匹配器M = p.matcher(线);
而(m.find()){
   numbers.add(m.group());
}


解决方案

 模式P = Pattern.compile( -  \\\\ D +?);
匹配M = p.matcher(还有比-2和小于12号的详细点击这里);
而(m.find()){
  的System.out.println(m.group());
}

...打印-2和12。


- ?相匹配的领先的负号 - 可选。 \\ d匹配一个数字,我们需要在Java字符串写入\\作为\\虽然。因此,\\ D + 1相匹配更多个数字

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:

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());
}

... prints -2 and 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 more more digits

这篇关于如何从一个字符串中提取号码,并得到int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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