In JavaScript there is a method isdigit () used to determine whether a string is a number, in the Java string processing method does not have such a method, it is often necessary to use, so the Internet search, sorted out two with regular expression matching method, as follows:
//determines whether a string is numeric Public Booleanisdigit (String strnum) {returnStrnum.matches ("[0-9]{1,}"); } //determines whether a string is numeric Public Booleanisdigit (String strnum) {pattern pattern= Pattern.compile ("[0-9]{1,}"); Matcher Matcher=Pattern.matcher ((charsequence) strnum); returnmatcher.matches (); }//Intercept Numbers Publicstring Getnumbers (string content) {pattern pattern= Pattern.compile ("\\d+"); Matcher Matcher=pattern.matcher (content); while(Matcher.find ()) {returnMatcher.group (0); } return""; } //Intercept non-digital Publicstring Splitnotnumber (string content) {pattern pattern= Pattern.compile ("\\d+"); Matcher Matcher=pattern.matcher (content); while(Matcher.find ()) {returnMatcher.group (0); } return""; }
//determines whether a string contains a number Public Booleanhasdigit (String content) {BooleanFlag =false; Pattern P= Pattern.compile (". *\\d+.*"); Matcher m=p.matcher (content); if(M.matches ()) {flag=true; } returnFlag;}
Three ways to determine whether a string is a number in Java:
1. Functions with Java
Public Static Boolean isnumeric (String str) { for (int i = str.length ();-I >= 0 ;) { if (! Character.isdigit (Str.charat (i))) { returnfalse; } } return true ; }
2. Using regular expressions
Public Static Boolean isnumeric (String str) { = Pattern.compile ("[0-9]*"); return pattern.matcher (str). matches (); }
3. Using ASCII code
Public Static Boolean isnumeric (String str) { for (int i = str.length ();-I >= 0 ;) { int chr = Str.charat (i); if (Chr < | | chr >) return false ; } return true ; }
In Java, determine whether a string is "both numeric" and "contains numbers" and "intercepts numbers"