- 使用str.matches(".*\\d+.*")判斷字串內是否有數字
如 boolean containsNum1 = testStr1.matches(".*\\d+.*"); - 判斷字串內的數字所在的index
先建立pattern、建立比對用的matcher,最後進行比對
public class HelloWorld{
public static void main(String []args){
String testStr1 = "ABC1",
testStr2 = "ABC99",
testStr3 = "ABCDE";
//判斷字串內是否有數字
boolean containsNum1 = testStr1.matches(".*\\d+.*");
boolean containsNum2 = testStr2.matches(".*\\d+.*");
boolean containsNum3 = testStr3.matches(".*\\d+.*");
System.out.println("containsNum1="+containsNum1);
System.out.println("containsNum2="+containsNum2);
System.out.println("containsNum3="+containsNum3);
//以下兩種寫法都可以判斷出是否存在數字
String patternStr1 = "\\d+";
String patternStr2 = "[0-9]+";
//建立pattern
Pattern pattern1 = Pattern.compile(patternStr1);
Pattern pattern2 = Pattern.compile(patternStr2);
//建立比對用的matcher
Matcher matcher1 = pattern1.matcher(testStr1);
Matcher matcher2 = pattern2.matcher(testStr2);
Matcher matcher3 = pattern1.matcher(testStr3);
//取得數字所在的index,預設值為-1表示不存在,若存在會被設定成>0的整數
int indexOfStr1 = -1,
indexOfStr2 = -1,
indexOfStr3 = -1;
if(matcher1.find()){
indexOfStr1 = matcher1.start();
}
System.out.println("字串"+testStr1+"的數字所在的index為"+indexOfStr1);
if(matcher2.find()){
indexOfStr2 = matcher2.start();
}
System.out.println("字串"+testStr2+"的數字所在的index為"+indexOfStr2);
if(matcher3.find()){
indexOfStr3 = matcher3.start();
}
//此輸出結果為-1,表示不存在數字
System.out.println("字串"+testStr3+"的數字所在的index為"+indexOfStr3);
}
}
線上執行請參考(點選左上角的Execute可看執行結果):http://tpcg.io/4z93pF
執行結果:
containsNum1=true
containsNum2=true
containsNum3=false
字串ABC1的數字所在的index為3
字串ABC99的數字所在的index為3
字串ABCDE的數字所在的index為-1
--------------------------------
參考網址
1. Check if a String contains numbers Java
以Java檢查String中是否存在數字
2. How to check if a string contains only digits in Java [duplicate]
如何以Java檢查String終只存在數字
3. Can Java String.indexOf() handle a regular expression as a parameter?
Java的String.indexOf()是否可傳入正規表示式
4. Why isn't the Java matches method working? (Java pattern matching)
為何Java的matches方法不能用
Copyright © 2019 JavaSparrowK All rights reserved.
版權所有‧謝絕轉載
以Java檢查String中是否存在數字
2. How to check if a string contains only digits in Java [duplicate]
如何以Java檢查String終只存在數字
3. Can Java String.indexOf() handle a regular expression as a parameter?
Java的String.indexOf()是否可傳入正規表示式
4. Why isn't the Java matches method working? (Java pattern matching)
為何Java的matches方法不能用
Copyright © 2019 JavaSparrowK All rights reserved.
版權所有‧謝絕轉載
沒有留言:
張貼留言