从字符串中提取整数部分

25

如何最好地从字符串中提取整数部分?

Hello123

如何获取123部分?你可以使用Java的Scanner进行一些技巧性操作,不过有没有更好的方法呢?


会出现像“123Hello456”这样的实例吗? - Ascalonian
9个回答

46

如前所述,请尝试使用正则表达式。这应该会有所帮助:

String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123

然后你只需要将其转换为 int(或 Integer)即可。


1
我实际上需要执行 value.replaceAll("[A-z]+", ""); - SedJ601
1
@MasterHD - 你有包含插入符号吗?我刚刚运行了这个程序,它正常返回了“123”。 - Ascalonian

26

我相信你可以这样做:

Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();

编辑:Carlos提出了使用useDelimiter的建议


1
在哪个命名空间可以找到Scanner。 - Paul Creasey
是的,这不一定是最流畅或最优雅的方法,但应该可以工作。甚至在扫描器文档中也使用了它,网址为http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html。 - Brian Hasden
2
nextInt 的文档说明:“如果下一个标记无法转换为有效的整数,则此方法将抛出 InputMismatchException”,这适用于 Hello123。可以使用 in.useDelimiter("[^0-9]+");忽略非数字。 - user85421
好的,确实。对此感到抱歉。忘记了默认分隔符的事情。这就是我没有先试用它的后果。 - Brian Hasden

11

为什么不直接使用正则表达式来匹配您想要的字符串部分呢?

[0-9]

那就是你需要的全部内容,再加上它所需的任何周围字符。

查看http://www.regular-expressions.info/tutorial.html以了解正则表达式的工作原理。

编辑:我想说,对于这个示例,正则表达式可能有点过头了,如果另一个提交者发布的代码确实有效...但我仍然建议普遍学习正则表达式,因为它们非常强大,并且将比我愿意承认的更有用(在尝试了多年之后)。


4

虽然我知道这是一个6年前的问题,但我为那些想要避免现在学习正则表达式的人提供一个答案(你应该学习)。这种方法还可以返回数字之间的数字(例如,HP123KT567将返回123567)。

    Scanner scan = new Scanner(new InputStreamReader(System.in));
    System.out.print("Enter alphaNumeric: ");
    String x = scan.next();
    String numStr = "";
    int num;

    for (int i = 0; i < x.length(); i++) {
        char charCheck = x.charAt(i);
        if(Character.isDigit(charCheck)) {
            numStr += charCheck;
        }
    }

    num = Integer.parseInt(numStr);
    System.out.println("The extracted number is: " + num);

4
假设您想要一个尾随数字,可以使用以下方法:
import java.util.regex.*;

public class Example {


    public static void main(String[] args) {
        Pattern regex = Pattern.compile("\\D*(\\d*)");
        String input = "Hello123";
        Matcher matcher = regex.matcher(input);

        if (matcher.matches() && matcher.groupCount() == 1) {
            String digitStr = matcher.group(1);
            Integer digit = Integer.parseInt(digitStr);
            System.out.println(digit);            
        }

        System.out.println("done.");
    }
}

好的,它可以适用于您的示例和“小”数字。但对于无法适应int的大数字,它显然会失败。 - Michael Easter

4

一开始我认为Michael的正则表达式是可能最简单的解决方案,但仔细想了想,只需要使用"\d+"并使用Matcher.find()而不是Matcher.matches()即可:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Example {

    public static void main(String[] args) {
        String input = "Hello123";
        int output = extractInt(input);

        System.out.println("input [" + input + "], output [" + output + "]");
    }

    //
    // Parses first group of consecutive digits found into an int.
    //
    public static int extractInt(String str) {
        Matcher matcher = Pattern.compile("\\d+").matcher(str);

        if (!matcher.find())
            throw new NumberFormatException("For input string [" + str + "]");

        return Integer.parseInt(matcher.group());
    }
}

3

这个对我完美地起作用了。

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

输出:

1234
567
890

0
String[] parts = s.split("\\D+");    //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
} 

0
我们可以简单地使用正则表达式从字符串中提取整数值。
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));

在这里,您可以将所有字符串值替换为空值,然后将字符串解析为整数值。此外,您可以使用整数值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接