2017-05-04 84 views
-2

Hy,这里只是一个很快的例子,有没有人知道一个百分比和另一个数字的良好正则表达式?我想在一个XML Schema来使用它..用百分比和int表示的正则表达式

应符合:

-1 
100.00 
20.00 
20.0 
10.0 
20 
99.0 
66.4 
0.00 

所以应该匹配百分比或-1

我的做法行不通......

([/-1]{1}|\d{1,3}\.\d{1,2}) 

谢谢!

+0

如果我得到你的权利,你需要'-1 | [0-9] {1,2}(\ [ 0-9] {1,2})?| 100(\。00)?' –

回答

0
(-1\n|\b(100|\d{1,2})(\n|(\.\d{1,2}))) 

说明:

 

(-1\n|     // when not percentage OR ... 
    \b     // word boundary - must not be other symbols in front 
     (100|   // when integer part is equal to 100 OR ... 
      \d{1,2}  // when integer part is number between 0 and 99 
     )    // then after integer part must follow: 
     (\n|    // new line symbol OR ... 
      (\.\d{1,2}) // dot symbol AND fractional part composed of 0 and 99 
     ) 
) 

+0

匹配'999.99'。 – ClasG

+0

固定解决方案 - 现在可以避免这种情况 –

1

对于正则表达式,我通常使用并建议将MDN作为参考。

话虽这么说,如果我明白你正在尝试做这会为你工作: /(?=\s+|^)(?:-1|100(?:\.0+)?|\d{1,2}(?:\.\d{1,})?)(?=\s+)/gm

这将匹配什么都没有或白色空格前后 (?=\s+|^) content (?=\s+) 您可以选择更改的字符串到^(?: content)$如果你想每个数字是每一行上唯一的东西。

凡内容是任何的:

  • -1(-1
  • 100任选被folowed “”和一个或多个0(100(?:\.0+)?
  • 1或2个数字,可选后跟“。”。和1个或多个小数(\d{1,2}(?:\.\d{1,})?

你可以改变的{1,}的结局{1,X}其中X是要匹配小数的最大数量。

匹配结果检查RegExr

+0

您的正则表达式匹配'1212.123'或'abc1212.123xyz' – Toto

+0

@Toto感谢您的评论!我想我解决了这个问题。让我知道如果你发现新的正则表达式的其他问题:) – ioakeimo

+0

它仍然存在一些错误,它匹配'100.111' – Toto