gpt4 book ai didi

java - 正则表达式中数字的重叠测试?

转载 作者:行者123 更新时间:2023-12-01 04:12:16 24 4
gpt4 key购买 nike

我在这里遇到的挑战超出了我的正则表达式范围。如果有人有建议,我们将不胜感激。我一直无法找到类似的东西,我不确定它是否可行。我在java中使用以下表达式:

"(?i)-?(([1-9]+[0-9]*)|0)(\\.[0-9]*[1-9]+)?(e-?[0-9]+)?"

验证长字符串(最多 255 个字符),以确认它们至少符合允许的数值(不一定适合任何类型的计算)并允许使用科学计数法选项。 BigDecimal 类没有完成我需要的所有操作,因此需要对小数部分中的前导零和尾随零进行额外检查,因为该值必须符合最简化的数字表示形式,并遵循可预测的协议(protocol)而不进行任何更改。以下所有内容都返回我期望的结果:

String allowance = "(?i)-?(([1-9]+[0-9]*)|0)(\\.[0-9]*[1-9]+)?(e-?[0-9]+)?" ;

System.out.println("0".matches(allowance)) ; // assert true. Confirm default
System.out.println("-42".matches(allowance)) ; // assert true. Confirm integers only
System.out.println("0.2e543".matches(allowance)) ; // assert true
System.out.println("1e543".matches(allowance)) ; // assert true
System.out.println("0.2000e543".matches(allowance)) ; // assert false : trailing zeros after fractional .2
System.out.println(".2e543".matches(allowance)) ; // assert false : missing the leading zero
System.out.println("e543".matches(allowance)) ; // assert false : malformed
System.out.println("0001e543".matches(allowance)) ; // assert false : leading zeros in the integer
System.out.println("1.0".matches(allowance)) ; // assert false : easiest match is "1"
System.out.println("0.0".matches(allowance)) ; // assert false : easiest match is "0"

所有这些都很好,但我无法用同一个表达式来理解这两者。也许其中之一,但不能两者兼而有之:

System.out.println("-0".matches(allowance)) ;   // Supposed to be FALSE - Should just be "0"
System.out.println("0e543".matches(allowance)) ; // Supposed to be FALSE - "0" integer rules out the exponent segment so the easiest match would be "0"

是否可以捕获段“-?(([1-9]+[0-9])|0)(\.[0-9][1-9] +)?”作为两个独立但重叠的测试:1)排除“-0”,但前提是该值没有小数值(即-0.5是允许的),然后跳到2)排除下一个“如果整数值在测试中返回为“0”,则 e543"指数?

最佳答案

你可以试试这个:

"(?i)(0|-?([1-9][0-9]*)(\\.[0-9]*[1-9])?(e-?[1-9][0-9]*)?|-?0\\.[0-9]*[1-9](e-?[1-9][0-9]*)?)"

基本上,您接受以下任何一项:

  • 零,不带符号、小数或指数
  • 带有可选符号、小数或指数的非零数字
  • 一个零,带有必需的小数和可选的符号或指数

这是一个demonstration .

关于java - 正则表达式中数字的重叠测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com