簡體   English   中英

如何使用正則表達式限制小數點之前/之后/以及小數點后的位數?

[英]How to limit the number of digits before/after/ a decimal point and also overall with regex?

我正在嘗試檢查數字值是否具有特定數量的數字。

  1. 總體上不應超過19位數字
  2. 小數點(整數部分)前不得超過17位數字
  3. 小數點后的數字(小數部分)不得超過4位
  4. 可以有一個小數點
  5. 前面可以有+或-

有效的例子:

  • 1
  • 1.0
  • 0.0
  • 12345678901234567.12
  • 12345678901234567.12
  • -12345678901234567.12
  • 123456789012345.1234
  • 123456789012345.1234
  • -123456789012345.1234

無效的例子

  • 1234567890123456.1234 //因為有20位數字
  • 123456789012345678.1 //因為小數點前有超過17位數字
  • 1.12345 //因為小數點后有4位以上的數字

我已經嘗試了本教程中的示例,但無法按照我的意願使它們工作。 我想我很難理解如何使用前瞻性/環顧性,因為這部分並不會真正做到我想要的:

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM