正则表达式本身不在另一个数字中找到0。删除空格和“0”

时间:2015-12-08 19:24:07

标签: regex replace find

我需要找到只有空格或0的实例 NOT 01或10或任何其他包含0的数字只是一个孤立的0

我知道这会发现任何非零数字(01表示可以,10表示) 但出于某种原因,采取相反的措施并不成立

^(\d*[1-9]\d*)$

查找示例

  • 0
  • [空格可选] 0 [空格可选]
  • [空格] [空格可选]

什么找不到

  • 01
  • 10
  • 125510456

5 个答案:

答案 0 :(得分:1)

这是一种方法:

re = /
  ^
  (?!.*0.*0) # at most one 0
  [0 ]+ # all chars must be 0 or space
  $
/x

["0", " 0 ", "0 ", " 0", " ", "  "].all?{|s| s.match re}
#=> true
["01", "00", "10", "125510456"].any?{|s| s.match re}
#=> false

答案 1 :(得分:0)

I have it ALMOST figured out This will find 0 by itself

transform

And this will do the full replace of whitespace or 0 by itself

^([0]|\s)$

QUESTION: Am I missing something with the spaces? Did I make spaces before and after optional? It seems to work here

http://www.regextester.com/21 (substitute for the regex above)

答案 2 :(得分:0)

根据你的评论,匹配if一行只有一个0字符或任意数量的空格(仅限空格!)。

^(0|\ +)$

DEMO

答案 3 :(得分:0)

我认为您可能正在寻找空白边界类型的执行。

condition = -1 condition1 = 3 x = 2 condition2 = 5 y = 4 while not condition == 1 and not condition1 > x and not condition2 > y: print "hey" condition = 1 condition1 = 3 x = 2 while not condition == 1 and not condition1 > x: print "hey"

格式化:

\s?(?<!\S)0(?!\S)\s?|\s\s?

答案 4 :(得分:0)

^([0]|\s)$
     

问题:我是否遗漏了空格?我是否在可选项之前和之后创建了空格?

此表达式匹配单个零和单个空格;它既没有在空间之前或之后与空间匹配零。

简单表达式/^\s*0?\s*$/将匹配字符串

  • ^\s*以任意数量的空白字符开头
  • 0?可能为零
  • \s*$以任意数量的空白字符结尾

var texts = [ "0", "  0  ", "   ", "What NOT to find", "01", "10", "125510456"];
for (i in texts)
  document.write(texts[i].replace(/^\s*0?\s*$/, '"$&" MATCHED'), "<p>");