Java extracts numbers from a string
Give you a string that contains numbers, such as:
String s= "EERT343DFG56756DTRY66FGGG89DFGF";
So how do we extract the numbers? There are generally several methods, regular expressions, collection classes, and methods provided by the string class.
1 methods provided by the String class:
Package test exercise; Import java.util.*; public class Get_stringnum {
/** *2012.6.2 */public static void main (string[] args) {String str = "Love23next234csdn3423javaeye"; Str=str.trim (); S Tring str2= ""; if (str! = NULL &&! "". Equals (str)) {for (int i=0;i<str.length (); i++) {if (Str.charat (i) >=48 && str.charat (i) <=57) {str2+= Str.charat (i); }}} System.out.println (STR2); } }
Output
232343423
This method has an obvious disadvantage, can only extract the numbers together, can not be extracted separately. Of course it can be improved, interested friends can try.
2 Regular Expressions
Import java.util.*; Import Java.util.regex.Matcher; Import Java.util.regex.Pattern; public class Get_stringnum {
/** *2012.6.2 */public static void main (string[] args) {String a= "Love23next234csdn3423javaeye"; String regex= "[^0-9]"; Pattern p = pattern.compile (regEx); Matcher m = P.matcher (a); System.out.println (M.replaceall (""). Trim ());}}
Output
232343423
Pattern, Matcher is the two classes in the Java.util.regex software package, you can consult the API for specific usage. It is also not possible to extract numbers individually.
3 Collection Class Library
Import java.util.*; Import Java.util.regex.Matcher; Import Java.util.regex.Pattern; public class Get_stringnum {
/** *2012.6.2 */public static void main (string[] args) {String a= "Love23next234csdn3423javaeye"; list<string> digitlist = new arraylist<string> (); Pattern p = pattern.compile ("[^0-9]"); Matcher m = P.matcher (a); String result = M.replaceall (""); for (int i = 0; i < result.length (); i++) {Digitlist.add (result.substring (i, i+1));} System.out.println (digitlist); } }
Output
[2, 3, 2, 3, 4, 3, 4, 2, 3]
The same idea:
Import java.util.*; Import Java.util.regex.Matcher; Import Java.util.regex.Pattern; public class Get_stringnum {
/** *2012.6.2 */public static void main (string[] args) {String a= "Love23next234csdn3423javaeye"; list<string> ss = new arraylist<string> (); For (String sss:s.replaceall ("[^0-9]", ","). Split (",")) {if (Sss.length () >0) Ss.add (SSS); } System.out.print (ss); } }
Output
[2, 3, 2, 3, 4, 3, 4, 2, 3]
Java intercepts numbers in a string