Java 如何从字符串中提取数字并获得整数数组?
我有一个字符串变量(基本上是一个英语句子,数字的数目不确定),我想将所有数字提取到一个整数数组中。我想知道是否有正则表达式的快速解决方案Java 如何从字符串中提取数字并获得整数数组?,java,arrays,regex,string,Java,Arrays,Regex,String,我有一个字符串变量(基本上是一个英语句子,数字的数目不确定),我想将所有数字提取到一个整数数组中。我想知道是否有正则表达式的快速解决方案 我使用了肖恩的解决方案,并对其进行了轻微更改: LinkedList<String> numbers = new LinkedList<String>(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(line); while (m.find()) {
我使用了肖恩的解决方案,并对其进行了轻微更改:
LinkedList<String> numbers = new LinkedList<String>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
numbers.add(m.group());
}
LinkedList编号=新建LinkedList();
模式p=模式。编译(\\d+);
匹配器m=p.匹配器(线);
while(m.find()){
添加(m.group());
}
对于有理数,使用这个:([0-9]+[0-9]*)|([0-9]*.[0-9]+)|([0-9]+)
。。。打印-2
和12
-??匹配前导负号--可选\d匹配一个数字,但我们需要将
\
写成Java字符串中的\\
。因此,\d+匹配一个或多个数字
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,但这涉及到双反斜杠转义,这使其更难阅读
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();
这是用于提取保留小数的数字的我建议检查ASCII值以从字符串中提取数字 假设您有一个输入字符串作为myname12345,如果您只想提取数字12345,您可以首先将字符串转换为字符数组,然后使用以下伪代码
for(int i=0;i 如果(a[i]>=48&&a[i]如何使用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(" ")));
输出:
[-1, -2, 455, 0, 4]
描述
[
和]
分隔一组要单独匹配的字符,即在任何顺序中只进行一次
^
用于集合开头的特殊标识符,用于指示匹配分隔集合中不存在的所有字符,而不是集合中存在的所有字符
+
在一次和无限次之间,尽可能多次,根据需要回馈
-?
字符之一“-”和“?”
0-9
介于“0”和“9”之间的字符
接受的答案检测数字,但不检测格式化的数字,如2000,也不检测小数,如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);
Pattern p=Pattern.compile(“-?\\d+(,\\d+)*?\\.?\\d+”);
列表编号=新的ArrayList();
Matcher m=p.Matcher(“政府向2000所学校分发了480万本教科书”);
而(m.find()){
添加(m.group());
}
系统输出打印项次(数字);
输出:
[4.82000]
使用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]
如果没有负数,可以去掉replaceAll
(并在filter
中使用!s.isEmpty()
),因为这只是为了正确地拆分2-34
之类的内容(也可以在split
中使用regex来处理,但这相当复杂)
Arrays.stream
将我们的字符串[]
转换为一个字符串
filter
除去前导和尾随的空字符串以及任何不是数字一部分的-
mapToInt(Integer::parseInt).toArray()
对每个字符串调用parseInt
,以给我们一个int[]
或者,Java 9有一个方法,该方法应允许以下内容:
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]
目前,这两种方法都不是像其他答案中所示的那样,仅使用模式
/匹配器
循环结果的一个大改进,但是如果您想使用更复杂的操作来进行后续操作,则应该更简单,因为使用流可以大大简化操作。我发现这个表达式很简单东部标准
String[] extractednums = msg.split("\\\\D++");
使用此函数提取所有实数
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;
}
}
publicstaticarraylistextracternumbersnoder(stringstr){
str+='a';
double[]returnArray=新的double[]{};
ArrayList=新建ArrayList();
字符串singleNum=“”;
布尔numStarted;
for(字符c:str.toCharArray()){
if(国际标准编号(c)){
singleNum+=c;
}否则{
如果(!singleNum.equals(“”){//number结束
list.add(Double.valueOf(singleNum));
System.out.println(singleNum);
singleNum=“”;
}
}
}
退货清单;
}
公共静态布尔isNumber(字符c){
if(Character.isDigit(c)| | c='-'| | c='+'| | c='.')){
返回true;
}否则{
返回false;
}
}
表示实数的分数和分组字符可能在不同语言之间有所不同。根据语言的不同,相同的实数可能以非常不同的方式书写
德语中的数字是200万
2000000.00
还有英语
2.000.000,00
以与语言无关的方式从给定字符串中完全提取实数的方法:
public List<BigDecimal> extractDecimals(final String s, final char fraction, final char grouping) {
List<BigDecimal> decimals = new ArrayList<BigDecimal>();
//Remove grouping character for easier regexp extraction
StringBuilder noGrouping = new StringBuilder();
int i = 0;
while(i >= 0 && i < s.length()) {
char c = s.charAt(i);
if(c == grouping) {
int prev = i-1, next = i+1;
boolean isValidGroupingChar =
prev >= 0 && Character.isDigit(s.charAt(prev)) &&
next < s.length() && Character.isDigit(s.charAt(next));
if(!isValidGroupingChar)
noGrouping.append(c);
i++;
} else {
noGrouping.append(c);
i++;
}
}
//the '.' character has to be escaped in regular expressions
String fractionRegex = fraction == POINT ? "\\." : String.valueOf(fraction);
Pattern p = Pattern.compile("-?(\\d+" + fractionRegex + "\\d+|\\d+)");
Matcher m = p.matcher(noGrouping);
while (m.find()) {
String match = m.group().replace(COMMA, POINT);
decimals.add(new BigDecimal(match));
}
return decimals;
}
public List extractDecimals(最终字符串、最终字符分数、最终字符分组){
列表小数=新的ArrayList();
//删除分组字符以便于正则表达式提取
StringBuilder NoGroup=新建StringBuilder();
int i=0;
而(i>=0&&i=0&&Character.isDigit(s.charAt(prev))&&
nextpublic 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;
}
}
public List<BigDecimal> extractDecimals(final String s, final char fraction, final char grouping) {
List<BigDecimal> decimals = new ArrayList<BigDecimal>();
//Remove grouping character for easier regexp extraction
StringBuilder noGrouping = new StringBuilder();
int i = 0;
while(i >= 0 && i < s.length()) {
char c = s.charAt(i);
if(c == grouping) {
int prev = i-1, next = i+1;
boolean isValidGroupingChar =
prev >= 0 && Character.isDigit(s.charAt(prev)) &&
next < s.length() && Character.isDigit(s.charAt(next));
if(!isValidGroupingChar)
noGrouping.append(c);
i++;
} else {
noGrouping.append(c);
i++;
}
}
//the '.' character has to be escaped in regular expressions
String fractionRegex = fraction == POINT ? "\\." : String.valueOf(fraction);
Pattern p = Pattern.compile("-?(\\d+" + fractionRegex + "\\d+|\\d+)");
Matcher m = p.matcher(noGrouping);
while (m.find()) {
String match = m.group().replace(COMMA, POINT);
decimals.add(new BigDecimal(match));
}
return decimals;
}
Pattern p = Pattern.compile("\\b-?\\d+\\b");
Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
while (m.find()) {
System.out.println(m.group());
}
2
12
public static String extractNumberFromString(String number) {
String num = number.replaceAll("[^0-9]+", " ");
return num.replaceAll(" ", "");
}