简体   繁体   English

java中如何从输入字符串中提取数值

[英]how to extract numeric values from input string in java

How can I extract only the numeric values from the input string?如何仅从输入字符串中提取数值?

For example, the input string may be like this:例如,输入字符串可能是这样的:

String str="abc d 1234567890pqr 54897";

I want the numeric values only ie, "1234567890" and "54897" .我只想要数值,即"1234567890""54897" All the alphabetic and special characters will be discarded.所有字母和特殊字符都将被丢弃。

You could use the .nextInt() method from theScanner class:您可以使用Scanner类中的.nextInt()方法:

Scans the next token of the input as an int.将输入的下一个标记扫描为 int。

Alternatively, you could also do something like so:或者,您也可以执行以下操作:

String str=" abc d 1234567890pqr 54897";

Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find())
{
    System.out.println(m.group(1));
}
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
  matcher.find();
  System.out.println(matcher.group());
}

Split your string into char array using yourString.toCharArray();使用yourString.toCharArray();将字符串拆分为字符数组yourString.toCharArray(); Then iterate through the characters and use Character.isDigit(ch);然后遍历字符并使用Character.isDigit(ch); to identify if this is the numeric value.以确定这是否是数值。 Or iterate through whole string and use str.charAt(i) .或者遍历整个字符串并使用str.charAt(i) For eg:例如:

public static void main(String[] args) {
    String str = "abc d 1234567890pqr 54897";
    StringBuilder myNumbers = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            myNumbers.append(str.charAt(i));
            System.out.println(str.charAt(i) + " is a digit.");
        } else {
            System.out.println(str.charAt(i) + " not a digit.");
        }
    }
    System.out.println("Your numbers: " + myNumbers.toString());
}

You could do something like:你可以这样做:

Matcher m = Pattern.compile("\\d+").matcher(str);
while (m.find()) {
   System.out.println(m.group(0));
}

You can use str = str.replaceAll("replaced_string","replacing_string");您可以使用str = str.replaceAll("replaced_string","replacing_string");

String str=" abc d 1234567890pqr 54897";
String str_rep1=" abc d ";
String str_rep2="pqr ";
String result1=str.replaceAll("", str_rep1);
String result2=str.replaceAll(",",str_rep2);

also what npinti suggests is fine to work with. npinti 建议的内容也可以使用。

Example using java Scanner class使用 java Scanner 类的示例

import java.util.Scanner;

Scanner s = new Scanner( "abc d 1234567890pqr 54897" );
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
    s.nextInt(); // get int
}

If you do not want to use regex,如果您不想使用正则表达式,

String str = " abc d 1234567890pqr 54897";

char[] chars = new char[str.length()];

int i = 0;
for (int j = 0; j < str.length(); j++) {
    char c = str.charAt(j);
    if (Character.isDigit(c)) {
        chars[i++] = c;
        if (j != chars.length - 1)
            continue;
    }
    if (chars[0] == '\0')
        continue;
    String num = new String(chars).trim();
    System.out.println(num);
    chars = new char[str.length()];
    i = 0;

}

Output : 1234567890 54897输出:1234567890 54897

You want to discard everything except digits and spaces:您想丢弃除数字和空格之外的所有内容:

String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();

The extra calls clean up doubled and leading/trailing spaces.额外的调用会清理双倍和前导/尾随空格。

If you need an array, add a split:如果需要数组,请添加拆分:

String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");
        String line = "This order was32354 placed 343434for 43411 QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);
        String required = "";
        for(String st: str){
            System.out.println(st);
        }

By above code you will get all the numeric values.通过上面的代码,您将获得所有数值。 then you can merge them or what ever you wanted to do with those numeric values.然后你可以合并它们或者你想用这些数值做什么。

You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer , using a try / catch approach to handle the cases where parsing it is as a number fails.您可以在空格上拆分字符串以获取单个条目,循环遍历它们,并尝试使用Integer上的相关方法解析它们,使用try / catch方法来处理将其解析为数字失败的情况。 That is probably the most straight-forward approach.这可能是最直接的方法。

Alternatively, you can construct a regex to match only the numbers and use that to find them all.或者,您可以构建一个正则表达式来仅匹配数字并使用它来查找所有数字。 This is probably far more performant for a big string.对于大字符串,这可能性能更高。 The regex will look something like `\\b\\d+\\b'.正则表达式看起来像`\\ B \\ d + \\ B”。

UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that @npinti gives.更新:或者,如果这不是家庭作业或类似的作业(我假设您正在寻找自己实施它的线索,但这可能无效),您可以使用@npinti 提供的解决方案。 That's probably the approach you should take in production code.这可能是您在生产代码中应该采用的方法。

public static List<String> extractNumbers(String string) {
    List<String> numbers = new LinkedList<String>();
    char[] array = string.toCharArray();
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < array.length; i++) {
        if (Character.isDigit(array[i])) {
            stack.push(array[i]);
        } else if (!stack.isEmpty()) {
            String number = getStackContent(stack);
            stack.clear();
            numbers.add(number);
        }
    }
    if(!stack.isEmpty()){
        String number = getStackContent(stack);
        numbers.add(number);            
    }
    return numbers;
}

private static String getStackContent(Stack<Character> stack) {
    StringBuilder sb = new StringBuilder();
    Enumeration<Character> elements = stack.elements();
    while (elements.hasMoreElements()) {
        sb.append(elements.nextElement());
    }
    return sb.toString();
}

public static void main(String[] args) {
    String str = " abc d 1234567890pqr 54897";
    List<String> extractNumbers = extractNumbers(str);
    for (String number : extractNumbers) {
        System.out.println(number);
    }
}

Just extract the digits只需提取数字

String str=" abc d 1234567890pqr 54897";        

for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58)
        System.out.print(str.charAt(i));

Another version另一个版本

String str=" abc d 1234567890pqr 54897";        
boolean flag = false;
for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58) {
        System.out.print(str.charAt(i));
        flag = true;
    } else {
        System.out.print( flag ? '\n' : "");
        flag = false;
    }
public class ExtractNum

{

  public static void main(String args[])

  {

   String input = "abc d 1234567890pqr 54897";

   String digits = input.replaceAll("[^0-9.]","");

   System.out.println("\nGiven Number is :"+digits);

  }

 }
 public static String convertBudgetStringToPriceInteger(String budget) {
    if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
        double numbers = getNumericFromString(budget);
        if( budget.contains("Crore") ){
            numbers= numbers* 10000000;
        }else if(budget.contains("Lac")){
            numbers= numbers* 100000;
        }
        return removeTrailingZeroesFromDouble(numbers);
    }else{
        return "0";
    }
}

Get numeric value from alphanumeric string从字母数字字符串中获取数值

 public static double getNumericFromString(String string){
    try {
        if(!AndroidUtils.isEmpty(string)){
            String commaRemovedString = string.replaceAll(",","");
            return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
            /*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/

        }
    }catch (NumberFormatException e){
        e.printStackTrace();
    }
    return 0;
}

For eg .例如。 If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion .如果我通过 1.5 lac 或 15,0000 或 15 千万卢比,那么我们可以从这些函数中获得数值。 We can customize string according to our needs.我们可以根据需要自定义字符串。 For eg.例如。 Result would be 150000 in case of 1.5 Lac在 1.5 Lac 的情况下,结果将为 150000

String str = "abc d 1234567890pqr 54897";
str = str.replaceAll("[^\\d ]", "");

The result will be "1234567890 54897".结果将是“1234567890 54897”。

String str = "abc34bfg 56tyu";

str = str.replaceAll("[^0-9]","");

output: 3456输出:3456

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM