模式匹配器有效数字 Java

huangapple go评论63阅读模式
英文:

Pattern Matcher valid number java

问题

我想进行数字验证。规则如下:

  1. 数字可以以 +、- 或者无符号开头(被视为正数)。
  2. 不能以 0 开头。
  3. 可以有小数部分,用 . 或者 , 表示。
  4. 不能以 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:

  1. A number can start with + or - or nothing (it is taken as a positive number)
  2. Cannot start with 0
  3. Can have a fraction either . or ,
  4. 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])?$

请参阅正则表达式演示正则表达式图示

模式匹配器有效数字 Java

详细信息

  • ^ - 字符串的开始
  • [+-]? - 可选的+-
  • [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:

模式匹配器有效数字 Java

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.

huangapple
  • 本文由 发表于 2020年9月14日 21:59:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63885863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定