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

时间:2013-11-05 23:36:37

标签: java regex

我在这里遇到的挑战超出了我的正则表达范围。如果有人有任何建议,将不胜感激。我无法追踪到这样的事情,我不确定它是否可行。我在java中使用以下表达式:

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

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

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)排除下一个跟随“ e543“指数,如果整数值在测试中返回为”0“?

2 个答案:

答案 0 :(得分:0)

您是否考虑过使用前一对中的前瞻,不要使用第二次测试时要检查的那个?

http://www.regular-expressions.info/lookaround.html

答案 1 :(得分:0)

你可以试试这个:

"(?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