[英]How to check if a string contains only digits in Java
在 Java for String class 中有一個方法叫做 matches,如何使用這個方法使用正則表達式檢查我的字符串是否只有數字。 我嘗試了以下示例,但結果都返回了 false。
String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
嘗試
String regex = "[0-9]+";
或者
String regex = "\\d+";
根據 Java正則表達式, +
表示“一次或多次”, \d
表示“一個數字”。
注意:“雙反斜杠”是獲得單個反斜杠的轉義序列- 因此,java String 中的\\d
為您提供實際結果: \d
參考:
編輯:由於其他答案有些混亂,我正在編寫一個測試用例,並將詳細解釋更多內容。
首先,如果您對此解決方案(或其他解決方案)的正確性有疑問,請運行此測試用例:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
是不是需要在正則表達式中添加
^
和$
,所以它不會匹配 "aa123bb" ?
否。在 java 中, matches
方法(在問題中指定)匹配完整的字符串,而不是片段。 換句話說,沒有必要使用^\\d+$
(即使它也是正確的)。 請參閱最后一個否定測試用例。
請注意,如果您使用在線“正則表達式檢查器”,則其行為可能會有所不同。 要在 Java 中匹配字符串的片段,您可以改用find
方法,這里有詳細描述:
Java Regex中matches()和find()的區別
這個正則表達式不會也匹配空字符串
""
嗎?*
不會。正則表達式\\d*
會匹配空字符串,但\\d+
不會。 星號*
表示零或多個,而加號+
表示一個或多個。 請參閱第一個否定測試用例。
編譯正則表達式模式不是更快嗎?
是的。 編譯一次正則表達式 Pattern 確實更快,而不是每次調用matches
時,因此如果性能影響很重要,那么可以像這樣編譯和使用Pattern
:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
您還可以使用 Apache Commons 中的NumberUtil.isNumber(String str)
使用正則表達式在性能方面的成本很高。 嘗試將字符串解析為長值是低效且不可靠的,並且可能不是您需要的。
我的建議是簡單地檢查每個字符是否是數字,使用 Java 8 lambda 表達式可以有效地完成什么:
boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));
另一種尚未發布的解決方案:
String regex = "\\p{Digit}+"; // uses POSIX character class
您必須允許多個數字( +
號),如:
String regex = "[0-9]+";
String data = "23343453";
System.out.println(data.matches(regex));
Long.parseLong(data)
並捕獲異常,它處理減號。
盡管位數有限,但這實際上創建了一個可以使用的數據變量,我想這是最常見的用例。
我們可以使用Pattern.compile("[0-9]+.[0-9]+")
或Pattern.compile("\\d+.\\d+")
。 它們具有相同的含義。
模式 [0-9] 表示數字。 與“\d”相同。 '+' 表示它出現的次數更多。 '。' 對於整數或浮點數。
試試下面的代碼:
import java.util.regex.Pattern;
public class PatternSample {
public boolean containNumbersOnly(String source){
boolean result = false;
Pattern pattern = Pattern.compile("[0-9]+.[0-9]+"); //correct pattern for both float and integer.
pattern = Pattern.compile("\\d+.\\d+"); //correct pattern for both float and integer.
result = pattern.matcher(source).matches();
if(result){
System.out.println("\"" + source + "\"" + " is a number");
}else
System.out.println("\"" + source + "\"" + " is a String");
return result;
}
public static void main(String[] args){
PatternSample obj = new PatternSample();
obj.containNumbersOnly("123456.a");
obj.containNumbersOnly("123456 ");
obj.containNumbersOnly("123456");
obj.containNumbersOnly("0123456.0");
obj.containNumbersOnly("0123456a.0");
}
}
輸出:
"123456.a" is a String
"123456 " is a String
"123456" is a number
"0123456.0" is a number
"0123456a.0" is a String
根據 Oracle 的 Java 文檔:
private static final Pattern NUMBER_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}
參考org.apache.commons.lang3.StringUtils
public static boolean isNumeric(CharSequence cs) {
if (cs == null || cs.length() == 0) {
return false;
} else {
int sz = cs.length();
for(int i = 0; i < sz; ++i) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
}
In Java for String class, there is a method called matches with help of this method you can validate the regex expression along with your string.
String regex = "^[\\d]{4}$";
String value="1234";
System.out.println(data.matches(value));
**The Explanation for the above regex expression is:-**
'^' - 表示正則表達式的開始。
'[]' - 在這個里面你必須描述你自己的條件。
'\\d' - 只允許數字。您可以在括號內使用 '\\d' 或 0-9 兩者都是相同的。
{4} - 這個條件正好允許 4 位數字。 您可以根據需要更改數字。
$ - 表示正則表達式的結束。
注意:您可以刪除 {4} 並指定“+”表示一位或多位數字或“*”表示零次或多次數字或“?” 這意味着一次或沒有。
如需更多參考,請訪問此網站: https ://www.rexegg.com/regex-quickstart.html
我會將此正則表達式用於整數:
^[-1-9]\d*$
這也適用於其他編程語言,因為它更具體並且不會對不同編程語言如何解釋或處理正則表達式做出任何假設。
\\d+
正如@vikingsteve在 java 中指出的那樣,matches 方法匹配一個完整的字符串,而不是字符串的一部分。 換句話說,沒有必要使用 ^\d+$ (即使它是正則表達式的官方方式)。
在線正則表達式檢查器更加嚴格,因此它們的行為與 Java 處理正則表達式的方式不同。
試試這部分代碼:
void containsOnlyNumbers(String str)
{
try {
Integer num = Integer.valueOf(str);
System.out.println("is a number");
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("is not a number");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.