【发布时间】:2014-09-18 10:26:09
【问题描述】:
需要一个允许以下有效值的正则表达式。(只允许小数和数字)
有效:
.1
1.10
1231313
0.32131
31313113.123123123
无效:
dadadd.31232
12313jn123
dshiodah
【问题讨论】:
标签: java regex validation
需要一个允许以下有效值的正则表达式。(只允许小数和数字)
有效:
.1
1.10
1231313
0.32131
31313113.123123123
无效:
dadadd.31232
12313jn123
dshiodah
【问题讨论】:
标签: java regex validation
试试这个:
String input = "0.32131";
Pattern pat = Pattern.compile("\\d*\\.?\\d+");
Matcher mat = pat.matcher(input);
if (mat.matches())
System.out.println("Valid!");
else
System.out.println("Invalid");
【讨论】:
0.321.31是有效的
Pattern.compile() 是一个好主意。这样,我们只需要创建 一次,但可以根据需要多次匹配结果。这比使用String.matches() 更有效,后者每次调用时都会重新编译相同的表达式。
你可以试试正则表达式:
^(\d+|\d*\.\d+)$
* 使用Debuggex: Online visual regex tester 生成的图像。
这个正则表达式的解释:
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\d* digits (0-9) (0 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
* 来自Explain Regular Expressions的解释。
【讨论】:
如果您想严格限制允许的匹配:
^[0-9]*\.?[0-9]+$
解释:
^ # the beginning of the string
[0-9]* # any character of: '0' to '9' (0 or more times)
\.? # '.' (optional)
[0-9]+ # any character of: '0' to '9' (1 or more times)
$ # before an optional \n, and the end of the string
【讨论】: