[英]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.