Java 提取字符串中的整数部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1903252/
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
Extract Integer Part in String
提问by Verhogen
What is the best way to extract the integer part of a string like
提取字符串的整数部分的最佳方法是什么
Hello123
How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
你如何获得123部分。您可以使用 Java 的 Scanner 对其进行破解,有没有更好的方法?
采纳答案by Crowe T. Robot
Why don't you just use a Regular Expression to match the part of the string that you want?
为什么不直接使用正则表达式来匹配您想要的字符串部分?
[0-9]
That's all you need, plus whatever surrounding chars it requires.
这就是你所需要的,加上它需要的任何周围字符。
Look at http://www.regular-expressions.info/tutorial.htmlto understand how Regular expressions work.
查看http://www.regular-expressions.info/tutorial.html以了解正则表达式的工作原理。
Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).
编辑:我想说正则表达式对于这个例子可能有点过分,如果其他提交者发布的代码确实有效......但我仍然建议总体上学习正则表达式,因为它们非常强大,并且会比我想承认的更有用(在给他们一个机会之前等了几年之后)。
回答by Brian Hasden
I believe you can do something like:
我相信你可以做这样的事情:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
编辑:添加了卡洛斯的 useDelimiter 建议
回答by Ascalonian
As explained before, try using Regular Expressions. This should help out:
如前所述,尝试使用正则表达式。这应该有帮助:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
And then you just convert that to an int (or Integer) from there.
然后您只需从那里将其转换为 int(或 Integer)。
回答by Michael Easter
Assuming you want a trailing digit, this would work:
假设您想要一个尾随数字,这将起作用:
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.");
}
}
回答by ecto
I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():
我一直认为 Michael 的正则表达式是最简单的解决方案,但再想一想,如果您使用 Matcher.find() 而不是 Matcher.matches(),那么“\d+”就可以工作:
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());
}
}
回答by hackrush
Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567will return 123567)
虽然我知道这是一个 6 岁的问题,但我正在为那些现在不想学习正则表达式的人发布答案(顺便说一句)。这种方法还给出了数字之间的数字(例如,HP 123KT 567将返回 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);
回答by amir ansari
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]);
}
回答by Muhammad Maqsood
This worked for me perfectly.
这对我来说非常有效。
Pattern p = Pattern.compile("\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}
OutPut:
输出:
1234
567
890