英文:
Pattern Matcher valid number java
问题
我想进行数字验证。规则如下:
- 数字可以以 +、- 或者无符号开头(被视为正数)。
- 不能以 0 开头。
- 可以有小数部分,用 . 或者 , 表示。
- 不能以 0 结尾。
因此,可接受的数字包括:+123,-123,123,1023,123.03,123,03。
不可接受的数字包括:001,1.000,任何字母。
我已经在Dan的工具上构建了表达式,除了小数点后的部分,其他几乎都搞定了。非常感谢任何帮助。
表达式:(^(\+|-?)([1-9]+))([0-9]+)(\.|,?)
提前感谢。
Nikos
英文:
I want to have a number validation. Rules are:
- A number can start with + or - or nothing (it is taken as a positive number)
- Cannot start with 0
- Can have a fraction either . or ,
- Cannot end with 0
So acceptable numbers are: +123, -123, 123, 1023, 123.03, 123,03.
Non acceptable numbers are: 001, 1.000, any letters
I give you the expression that I ve built so far, on Dan's Tools. I have managed almost everything, except expressions after the the fraction. Every help is acceptable.
Expression: (^(\+|-?)([1-9]+))([0-9]+)(\.|,?)
Thanks in advance
Nikos
答案1
得分: 1
除了您的模式中缺少小数部分外,您的正则表达式将不会匹配单个数字,因为您使用了+量词对[1-9]和[0-9]进行了量化,要求至少有一个字符。
您可以使用以下正则表达式:
^[+-]?[1-9][0-9]*(?:[.,][0-9]*[1-9])?$
详细信息
^- 字符串的开始[+-]?- 可选的+或-[1-9]- 单个非零数字[0-9]*- 零个或多个数字(?:[.,][0-9]*[1-9])?- 可选的小数部分:.或,,然后是零个或多个数字,后面跟着一个非零数字$- 字符串的结束。
英文:
Except the fractional part that is missing in your pattern, your regex won't match single digit numbers as you quantified [1-9] and [0-9] with + quantifier requiring at least one char.
You can use
^[+-]?[1-9][0-9]*(?:[.,][0-9]*[1-9])?$
See the regex demo and the regex graph:
Details
^- start of string[+-]?- an optional+or-[1-9]- a single non-zero digit[0-9]*- zero or more digits(?:[.,][0-9]*[1-9])?- an optional fractional part:.or,and then zero or more digits followed with a single non-zero digit$- end of string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论