java regex separate numbers from strings
I have got strings like:
BLAH00001
DIK-11
DIK-2
MAN5
so all the strings are a kind of (sequence any characters)+(sequence of numbers)
and i want so开发者_运维百科mething like this:
1
11
2
5
in order to get those integer values, i wanted to separate the char sequence and the number sequence an do something like Integer.parseInt(number_sequence)
Is there something that does this job?
greetings
Try this:
public class Main {
public static void main(String[]args) {
String source = "BLAH00001\n" +
"\n" +
"DIK-11\n" +
"\n" +
"DIK-2\n" +
"\n" +
"MAN5";
Matcher m = Pattern.compile("\\d+").matcher(source);
while(m.find()) {
int i = Integer.parseInt(m.group());
System.out.println(i);
}
}
}
which produces:
1
11
2
5
String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
for(String g:a)
System.out.println(Integer.valueOf(g.split("^[A-Z]+\\-?")[1]));
/*******************************
Regex Explanation :
^ --> StartWith
[A-Z]+ --> 1 or more UpperCase
\\-? --> 0 or 1 hyphen
*********************************/
Pattern p = Pattern.compile("^[^0-9]*([0-9]+)$");
Matcher m = p.matcher("ASDFSA123");
if (m.matches()) {
resultInt = Integer.parseInt(m.group(1)));
}
Maybe you want to have a look to Java Pattern and Matcher:
- http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
- http://leepoint.net/notes-java/data/strings/40regular_expressions/26pattern-matcher.html
- http://answers.yahoo.com/question/index?qid=20071106173149AA4TUON
精彩评论