繁体   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