正则表达式 – 匹配不在字符类序列中的数字

huangapple go评论122阅读模式
英文:

Regex - to match number NOT in a sequence of character classes

问题

不匹配这个数字模式:

([0]?[0-6][0-6][0])
英文:

Sample file contents:

create 664 root utmp

I would like to match any number that is NOT this:

[0-6][0-4][0]

So it would match 664 and 641, but not 440 and 640.

My full regex is this:

^([\s]`*`?)create[\s]+?([0]?[0-6][0-6][0-6])[\s]+?(\w+?)[\s]+?(\w+?)[\s]`*`?$

But I would like to basically say:

  • match on not this:

    ([0]?[0-6][0-6][0-6])
    

答案1

得分: 1

我看了一下:如何使用正则表达式进行“反向匹配”?

并找到了:(?![0-6][0-4][0])[0-9]{3} 查看:https://regex101.com/r/D3JRfu/1

据我所见,这应该有效。

英文:

I looked at: How can I "inverse match" with regex?

and found: (?![0-6][0-4][0])[0-9]{3} see: https://regex101.com/r/D3JRfu/1

As far as I can see this works.

答案2

得分: 0

使用你样本中的正则表达式 [0]?[0-6][0-6][0-6],可以通过一些负断言来实现。必须使用边界断言来强制对数字的数量和值进行约束。

(?<!\d)(?![0]?[0-6][0-6][0-6](?!\d))\d+

当将第一个负向后瞻放入更大的正则表达式时,可以用 \s 替代。

(?<!\d)(?![0]?\s?[0-6]\s?[0-6]\s?[0-6](?!\d))\d+
英文:

Using the regex in your sample [0]?[0-6][0-6][0-6],
it can be done with a couple of negative assertions.
There has to be boundary assertions to force a constraint on the number of
digits as well as values.

(?&lt;!\d)(?![0]?[0-6][0-6][0-6](?!\d))\d+  

The first negative look behind can be replaced with a \s when its put in the larger regex.

 (?&lt;! \d )
 (?!
    
    [0]? [0-6] [0-6] [0-6] 
    (?! \d )
    
 )
 \d+ 

huangapple
  • 本文由 发表于 2023年3月12日 17:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定