一、判斷字元是否都是數字代碼
public static boolean isNumer(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
二、判斷字元是否都是數字或者某個字元(下面是.)組成代碼
public static boolean isNumer_char(String str){
Pattern pattern = Pattern.compile("[0-9.]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
三、判斷字元是否都是數字或者某幾個字元(下面是.lt)組成代碼
public static boolean isNumer_nchar(String str){
Pattern pattern = Pattern.compile("[0-9.lt]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
四、測試java代碼,運作結果
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static boolean isNumer(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
public static boolean isNumer_char(String str){
Pattern pattern = Pattern.compile("[0-9.]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
public static boolean isNumer_nchar(String str){
Pattern pattern = Pattern.compile("[0-9.lt]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
public static void main(String[] args) {
String i = "01229";
String j = "12523";
String m = "12j23";
String n = "12.23";
String r = "12..23";
String p = "12n23";
String t = "12lt23";
System.out.println("************isNumer************");
System.out.println(i+" isNumer:"+isNumer(i));
System.out.println(j+" isNumer:"+isNumer(j));
System.out.println(m+" isNumer:"+isNumer(m));
System.out.println(n+" isNumer:"+isNumer(n));
System.out.println("************isNumer_char************");
System.out.println(i+" isNumer_char:"+isNumer_char(i));
System.out.println(n+" isNumer_char:"+isNumer_char(n));
System.out.println(p+" isNumer_char:"+isNumer_char(p));
System.out.println(r+" isNumer_char:"+isNumer_char(r));
System.out.println("************isNumer_nchar************");
System.out.println(t+" isNumer_char:"+isNumer_char(t));
System.out.println(t+" isNumer_nchar:"+isNumer_nchar(t));
System.out.println("Hello, World");
}
}
************isNumer************
01229 isNumer:true
12523 isNumer:true
12j23 isNumer:false
12.23 isNumer:false
************isNumer_char************
01229 isNumer_char:true
12.23 isNumer_char:true
12n23 isNumer_char:false
12..23 isNumer_char:true
************isNumer_nchar************
12lt23 isNumer_char:false
12lt23 isNumer_nchar:true
Hello, World
五、參考文章
Android正規表達式及Pattern Matcher使用 #Android #Pattern - 簡書
android:java 判斷字元串是否全是數字_android 判斷純數字_龍騰騰的部落格-CSDN部落格