如何使用正则表达式限制小数点之前/之后/之后的位数以及整体的位数? [英] How to limit the number of digits before/after/ a decimal point and also overall with regex?

查看:28
本文介绍了如何使用正则表达式限制小数点之前/之后/之后的位数以及整体的位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查一个数值是否具有特定数量的数字.

I'm trying to check that a numeric value has a specific amount of digits.

  1. 总共不应超过 19 位
  2. 小数点前不能超过 17 位(整数部分)
  3. 小数点后不能超过 4 位(小数部分)
  4. 可以有小数点也可以没有
  5. 可以有前面的 + 或 - 或没有

有效示例:

  • 1
  • 1.0
  • .0
  • 12345678901234567.12
  • +12345678901234567.12
  • -12345678901234567.12
  • 123456789012345.1234
  • +123456789012345.1234
  • -123456789012345.1234

无效示例

  • 1234567890123456.1234//因为有20位
  • 123456789012345678.1//因为小数点前有17位以上
  • 1.12345//因为小数点后有4位以上

我已经尝试过本教程中的示例,但无法让它们以我喜欢的方式工作.我想我很难理解如何使用前瞻/环视,因为这部分不会真正做到我想要的:

I have tried the examples from this tutorial but can't get them to work how I'd like to. I think I have troubles understanding how to use look aheads/arounds since this part won't really do what I'd like it to:

@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代码中使用时记得使用双反斜杠.

You can use \A(?=.*\d)(?!(?:\D*\d){20,})[+-]?\d{0,17}(?:\.\d{1,4})?\z. Remember to use double backslashes when using it in java code.

  • \A - 匹配字符串的开头
  • (?=.*\d) 检查是否至少有一位数字(因为基本上所有内容都是可选的)
  • (?!(?:\D*\d){20,}) 检查数字不超过 19 位
  • [+-]? 匹配可选的 +-
  • \d{0,17} 匹配最多 17 位整数部分
  • (?:\.\d{1,4})? 最多匹配小数部分的 4 位数字,你可以使用 {0,4} 如果12. 有效
  • \z 匹配字符串的结尾
  • \A - matches start of string
  • (?=.*\d) check that there is at least one digit (because of basically everythin being optional)
  • (?!(?:\D*\d){20,}) check that there are no more than 19 digits
  • [+-]? match optional + or -
  • \d{0,17} match up to 17 digits integer part
  • (?:\.\d{1,4})? match up to 4 digits in the decimal part, you can use {0,4} if 12. is valid
  • \z match end of the string

这篇关于如何使用正则表达式限制小数点之前/之后/之后的位数以及整体的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆