[英]How to limit the number of digits before/after/ a decimal point and also overall with regex?
我正在嘗試檢查數字值是否具有特定數量的數字。
有效的例子:
無效的例子
我已經嘗試了本教程中的示例,但無法按照我的意願使它們工作。 我想我很難理解如何使用前瞻性/環顧性,因為這部分並不會真正做到我想要的:
@Test
public void testTutorialCode() {
//min two, max four digits for the whole expression
Pattern p = Pattern.compile("\\A(?=(?:[^0-9]*[0-9]){2,4})\\z");
assertFalse(p.matcher("+1234.0").matches());
assertTrue(p.matcher("12").matches());
assertTrue(p.matcher("12.12").matches());
assertTrue(p.matcher("+123.0").matches());
assertFalse(p.matcher("1234.0").matches());
}
您可以使用\\A(?=.*\\d)(?!(?:\\D*\\d){20,})[+-]?\\d{0,17}(?:\\.\\d{1,4})?\\z
。 記住在Java代碼中使用雙反斜杠。
\\A
匹配字符串的開頭 (?=.*\\d)
檢查是否至少有一位數字(因為基本上一切都是可選的) (?!(?:\\D*\\d){20,})
檢查不超過19位數字 [+-]?
匹配可選的+
或-
\\d{0,17}
匹配最多17位整數部分 (?:\\.\\d{1,4})?
最多匹配小數點后4位數字,如果12.
有效,則可以使用{0,4}
\\z
匹配字符串的結尾 嘗試這個 :
Pattern p = Pattern.compile("(-)?(\\+)?(\\d+)\\.(\\d+)");
Matcher m = p.matcher("1234567890123456.1234");
if(m.find()){
if(m.group(3).length()<=17 && m.group(4).length()<=4 && (m.group(3).length()+m.group(4).length()<20)){
System.out.println("Correct");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.