java中的字符串数

Ali*_*_IT 7 java string numbers

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

pol*_*nts 12

int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234
Run Code Online (Sandbox Code Playgroud)

请注意这将如何将来自字符串不同部分的数字"合并"为一个数字.如果你只有一个数字,那么这仍然有效.如果您只想要第一个数字,那么您可以这样做:

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

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


Pin*_*juh 8

使用以下RegExp(请参阅http://java.sun.com/docs/books/tutorial/essential/regex/):

\d+
Run Code Online (Sandbox Code Playgroud)

通过:

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
}
Run Code Online (Sandbox Code Playgroud)