[英]Regular expression to allow decimal places including .123 and 123. etc in Java
Friends朋友们
I have the following Regex "^[0-9]{1,12}+(\\\\.[0-9]{1,4})?$"
that allows the following values我有以下正则表达式
"^[0-9]{1,12}+(\\\\.[0-9]{1,4})?$"
允许以下值
123456789012.1234 which is a valid decimal value {12,4} 123456789012.1234 这是一个有效的十进制值 {12,4}
123456789012 which is a valid integer value etc 123456789012 这是一个有效的整数值等
but it doesn't allow value like .1235 etc , how should I modify above Regex so that it also allows values like .123 and 123. etc但它不允许像 .1235 等值,我应该如何修改上面的正则表达式,以便它也允许像.123 和 123等值。
I guess,我猜,
^(?:[0-9]{1,12}(?:\\.[0-9]{0,4})?|\\.[0-9]{0,4})$
might be somewhat close.可能有点接近。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "^(?:[0-9]{1,12}(?:\\.[0-9]{0,4})?|\\.[0-9]{0,4})$";
final String string = "123456789012.1234\n"
+ "123456789012\n"
+ ".1235\n"
+ ".123\n"
+ "123.\n"
+ ".12345\n"
+ "0.12345";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Full match: 123456789012.1234
Full match: 123456789012
Full match: .1235
Full match: .123
Full match: 123.
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com .如果你想简化/更新/探索表达式,它已在regex101.com 的右上角面板中进行了解释。 You can watch the matching steps or modify them in this debugger link , if you'd be interested.
如果您有兴趣,可以在此调试器链接中观看匹配步骤或修改它们。 The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
调试器演示了 RegEx 引擎如何逐步使用一些示例输入字符串并执行匹配过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.