我有:
^-?[0-9]\d*(\.\d+)?$
但需要它只允许最多3位小数。所以允许的值是:
+10.123
-10.123
10.123
10
+10
-10
10.1
10.12
不允许:
10.1234
10.123%
建议/建议的表达模式赞赏。
提前致谢。
答案 0 :(得分:2)
除了指定无限重复的*
和+
元字符外,正则表达式还允许您对{a,b}
的匹配数量设置特定限制构造。此处,a
是所需的最低匹配数,b
是最大匹配数。 a
和b
都是包含。
由于您需要匹配至少一个,最多三个数字,因此您需要将\d+
替换为\d{1,3}
:
^[+-]?[0-9]\d*(\.\d{1,3})?$
优化:掌握有效的正则表达式,您可以将[0-9]
替换为另一个\d
进行优化,并使用“{1}}”将其“折叠”为\d*
\d+
:
^[+-]?\d+(\.\d{1,3})?$
答案 1 :(得分:1)
^[+-]{0,1}\d*?(\.{0,1}\d{0,3})?$
应该有效
请参阅https://regex101.com/r/P6DBrW/1/了解正则表达式的解释
答案 2 :(得分:1)
^[+-]?\d+(\.\d{1,3})?$
请在此处查看:https://www.debuggex.com/r/BbCBL5pQWLxsD4a6
^ asserts position at start of a line
Match a single character present in the list below [+-]?
? Quantifier — Matches between zero and one times, as many times as possible,
giving back as needed (greedy)
+- matches a single character in the list +- (case sensitive)
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible,
giving back as needed (greedy)
1st Capturing Group (\.\d{1,3})?
? Quantifier — Matches between zero and one times, as many times as possible,
giving back as needed (greedy)
\. matches the character . literally (case sensitive)
\d{1,3} matches a digit (equal to [0-9])
{1,3} Quantifier — Matches between 1 and 3 times, as many times as possible,
giving back as needed (greedy)
$ asserts position at the end of a line
解释来自:{https://regex101.com/]
答案 3 :(得分:0)
^(?!0\d)\d*
(\.\d{1,4})?$