Java中从字符串中提取数字

7

我有一个类似于"ali123hgj"的字符串。我想要把其中的123转换成整数。在Java中该怎么做?


4
“abc123def567ghi”或“abcdef”怎么样? - kennytm
1
数字前面总是有三个字符,还是这只是一个例子? - lbedogni
它不仅仅是三个字符,它是0或更多个字符之间的数字。它可以是"123"、"sdfs"、"123fdhf"、"fgdkjhgf123"等。 - Ali_IT
6个回答

14
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234

请注意,这将把来自字符串不同部分的数字“合并”成一个数字。如果您只有一个数字,那么这仍然有效。如果您只想要第一个数字,那么您可以像这样做:

int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42

正则表达式比较复杂,但基本上它会用第一个包含数字序列(带可选的减号)来替换整个字符串,然后使用Integer.parseInt将其解析为整数。


8
请使用以下正则表达式(参见http://java.sun.com/docs/books/tutorial/essential/regex/):
\d+

由:

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
}

1
这是Google Guava #CharMatcher的方式。
String alphanumeric = "12ABC34def";

String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234

String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef

如果您只关心匹配ASCII数字,请使用:
String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234

如果你只关心匹配拉丁字母,请使用
String letters = CharMatcher.inRange('a', 'z')
                         .or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef

0
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...
}

0
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;

输入 "asg123d ddhd-2222-33sds --- ---222 ss---33dd 234" 的结果是 [123, -2222, -33, -222, -33, 234]


0

你可以按照以下方式来完成:

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)));
}

它也很容易适应多个数字组。这段代码仅供参考:尚未经过测试。


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