java中的字符串数

我有类似“ali123hgj”的东西。 我想要123整数。 我怎么能在java中做到这一点?

使用以下RegExp(请参阅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 ints = new ArrayList(); // results while (matcher.find()) { // for each match ints.add(Integer.parseInt(matcher.group())); // convert to int } 
 int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", "")); // i == 1234 

注意这将如何将来自字符串的不同部分的数字“合并”为一个数字。 如果你只有一个数字,那么这仍然有效。 如果您只想要第一个数字,那么您可以执行以下操作:

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

正则表达式有点复杂,但在使用Integer.parseInt解析为整数之前,它基本上用它包含的第一个数字序列(带有可选的减号)替换整个字符串。

这是Google Guava #CharMatcher Way。

 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 

你可以沿着这些方向做:

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

它也很容易适应多个数字组。 该代码仅用于定位:它尚未经过测试。

 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... } 
 public static final List scanIntegers2(final String source) { final ArrayList result = new ArrayList(); // 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]