java java中字符串中的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2574604/
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
number out of string in java
提问by Ali_IT
I have something like "ali123hgj". i want to have 123 in integer. how can i make it in java?
我有类似“ali123hgj”的东西。我想要整数 123。我怎样才能在java中制作它?
回答by polygenelubricants
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\D", ""));
// i == 1234
Note how this will "merge" digits from different parts of the strings together into one number. If you only have one number anyway, then this still works. If you only want the first number, then you can do something like this:
请注意这将如何将来自字符串不同部分的数字“合并”为一个数字。如果无论如何你只有一个号码,那么这仍然有效。如果您只想要第一个数字,那么您可以执行以下操作:
int i = Integer.parseInt("x-42x100x".replaceAll("^\D*?(-?\d+).*$", ""));
// i == -42
The regex is a bit more complicated, but it basically replaces the whole string with the first sequence of digits that it contains (with optional minus sign), before using Integer.parseIntto parse into integer.
正则表达式有点复杂,但在Integer.parseInt用于解析为整数之前,它基本上用它包含的第一个数字序列(带有可选的减号)替换整个字符串。
回答by Pindatjuh
Use the following RegExp (see http://java.sun.com/docs/books/tutorial/essential/regex/):
使用以下 RegExp(参见http://java.sun.com/docs/books/tutorial/essential/regex/):
\d+
By:
经过:
final Pattern pattern = Pattern.compile("\d+"); // the regex
final Matcher matcher = pattern.matcher("ali123hgj"); // your string
final ArrayList<Integer> ints = new ArrayList<Integer>(); // results
while (matcher.find()) { // for each match
ints.add(Integer.parseInt(matcher.group())); // convert to int
}
回答by Kerem Baydo?an
This is the Google Guava #CharMatcherWay.
这是谷歌番石榴#CharMatcher方式。
String alphanumeric = "12ABC34def";
String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234
String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef
If you only care to match ASCII digits, use
如果您只关心匹配 ASCII 数字,请使用
String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234
If you only care to match letters of the Latin alphabet, use
如果您只想匹配拉丁字母表中的字母,请使用
String letters = CharMatcher.inRange('a', 'z')
.or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef
回答by Tomislav Nakic-Alfirevic
You could probably do it along these lines:
您可能可以按照以下方式进行:
Pattern pattern = Pattern.compile("[^0-9]*([0-9]*)[^0-9]*");
Matcher matcher = pattern.matcher("ali123hgj");
boolean matchFound = matcher.find();
if (matchFound) {
System.out.println(Integer.parseInt(matcher.group(0)));
}
It's easily adaptable to multiple number group as well. The code is just for orientation: it hasn't been tested.
它也很容易适应多个号码组。该代码仅用于定位:尚未经过测试。
回答by Chris Dennett
int index = -1;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i)) {
index = i; // found a digit
break;
}
}
if (index >= 0) {
int value = String.parseInt(str.substring(index)); // parseInt ignores anything after the number
} else {
// doesn't contain int...
}
回答by Michael Konietzka
public static final List<Integer> scanIntegers2(final String source) {
final ArrayList<Integer> result = new ArrayList<Integer>();
// in real life define this as a static member of the class.
// defining integers -123, 12 etc as matches.
final Pattern integerPattern = Pattern.compile("(\-?\d+)");
final Matcher matched = integerPattern.matcher(source);
while (matched.find()) {
result.add(Integer.valueOf(matched.group()));
}
return result;
Input "asg123d ddhd-2222-33sds --- ---222 ss---33dd 234" results in this ouput [123, -2222, -33, -222, -33, 234]
输入“asg123d ddhd-2222-33sds --- ---222 ss---33dd 234”导致此输出 [123, -2222, -33, -222, -33, 234]

