【问题标题】:Any numeric string except the string containing '000'除包含 '000' 的字符串外的任何数字字符串
【发布时间】:2019-04-22 11:12:27
【问题描述】:

如何匹配除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.

我应该使用负前瞻还是以下技术:

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

【问题讨论】:

  • 我们将不胜感激。
  • 例如(?!000)[0-9]{3}
  • @WiktorStribiżew;这不是解决方案。我试过regex101.com。检查以下字符串。数字可以是任意长度,而不仅仅是 3 位数字。 Check this data "111111112223445567889 111111112221111111122234455678890 1111111122211111111222344556788900 11111111222111111112223445567889 11111111222000111111112223445567889 00011111111222111111112223445567889 11111111222111111112223445567889000 00011111111222111111112223445567889000 000"
  • 听起来好像你想要^(?!000$)\d+$(不等于000demo)或^(?!\d*000)\d+$(不包含000demo
  • 这些是否按预期工作?

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


【解决方案1】:

你可以使用

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

查看regex demoRegulex graph

详情

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

【讨论】:

  • 请注意,与早期的解决方案相比,这是一个不太通用的解决方案。另一种解决方案可以嵌入到其他模式中,而这个不能。在这种情况下,为什么不直接使用!/000/
  • @ikegami;好的,但你能定义泛型吗?你的意思是这个不能嵌入或与其他正则表达式模式一起使用?
  • 它不能嵌入到其他模式中,所以只是一种复杂的说法/^\d$/ && !/000/
  • @BabarKamran 我的解决方案准确地回答了您的问题。如果您需要处理一些其他类型的字符串,请编辑问题。
  • 它不适用于纯文本正则表达式。代码解决方案不是OP所寻求的。
【解决方案2】:

你想要

$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;

【讨论】:

  • /?:(?!000).)*/mg 不排除具有 000 的字符串。我看到它只匹配 0 和 00,因此它匹配除 000 之外的所有数字。我想在一行中排除整个字符串。
  • 您需要提供某种形式的锚定,正如我所展示的。 (?:(?!000).)* 本身没有用,因为它可以匹配零个字符。就像我说的,(?:(?!000).)* 将用作更大模式的一部分。我提供了一个更简单的解决方案,不需要成为更大模式的一部分。
猜你喜欢
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 2010-12-17
  • 2016-01-26
  • 2013-04-08
  • 1970-01-01
相关资源
最近更新 更多