除包含'000'的字符串外的任何数字字符串

时间:2019-04-22 11:12:28

标签: regex pcre regex-negation regex-lookarounds regex-group

如何匹配除000以外的所有数字。就是

001234567502344001233400122300 is fine.
0123456750023440012334012230 is fine.
000123456750234400123340012230 is not fine.
001234567502344000123340012230 is not fine.
0012345675023440012334001223000 is not fine.
00123456750234400012334001223000 is not fine.
001002003004005006 is fine.
001 id fine
10 is fine.
01 is fine.
000 is not fine.

我应该使用否定的Lookaheads还是以下技术:

/(()|()|())/g

2 个答案:

答案 0 :(得分:1)

你想要

$string !~ /000/

测试:

$ perl -nle'printf "%s is %s\n", $_, !/000/ ? "fine" : "not fine"' <<'.'
001234567502344001233400122300
0123456750023440012334012230
000123456750234400123340012230
001234567502344000123340012230
0012345675023440012334001223000
00123456750234400012334001223000
001002003004005006
001
10
01
000
.
001234567502344001233400122300 is fine
0123456750023440012334012230 is fine
000123456750234400123340012230 is not fine
001234567502344000123340012230 is not fine
0012345675023440012334001223000 is not fine
00123456750234400012334001223000 is not fine
001002003004005006 is fine
001 is fine
10 is fine
01 is fine
000 is not fine

如果假设这是较大模式的一部分,则需要确保每个位置都不是000的开头。

(?:(?!000).)*

例如,

/^(?:(?!000).)*\z/

例如,

my @safe_numbers = $string_with_multiple_numbers =~ /\b(?:(?!000)\d)*\b/g;

答案 1 :(得分:1)

您可以使用

^(?!\d*000)\d+$

请参见regex demoRegulex graph

enter image description here

详细信息

  • ^-字符串的开头
  • (?!\d*000)-在字符串开头之后,000子字符串后面不能有任何0+数字
  • \d+-1个以上数字
  • $-字符串的结尾。