需要一个允许以下有效值的正则表达式。(只允许使用小数和数字)
有效:
.1
1.10
1231313
0.32131
31313113.123123123
无效:
dadadd.31232
12313jn123
dshiodah
答案 0 :(得分:4)
如果你想对你允许的比赛严格要求:
^[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
答案 1 :(得分:1)
试试这个:
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");
答案 2 :(得分:1)
您可以尝试使用正则表达式:
^(\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的解释。