regex - 正则表达式 - 连续 4 位数字,但不能全为零

标签 regex

我正在寻找一种只能使用正则表达式完成的解决方案。我知道这对于变量、子字符串等很容易。

即使我提到了 vim,我也在寻找 PCRE 风格的正则表达式语法。

我需要用 4 个数字来识别字符串,并且它们不能全是 0。因此,以下字符串将是匹配项:

0001 
1000 
1234 
0101

这不会:
0000

这是一个子字符串,它将出现在一个大字符串中的一个设定位置,如果这很重要的话;我认为不应该。例如
xxxxxxxxxxxx0001xxxxx
xxxxxxxxxxxx1000xxxxx
xxxxxxxxxxxx1234xxxxx
xxxxxxxxxxxx0101xxxxx
xxxxxxxxxxxx0101xxxxx
xxxxxxxxxxxx0000xxxxx

最佳答案

 (?<!\d)(?!0000)\d{4}(?!\d)

或者,更亲切/可维护/理智:
m{
     (?<! \d   )    # current point cannot follow a digit
     (?!  0000 )    # current point must not precede "0000"
     \d{4}          # match four digits at this point, provided...
     (?!  \d   )    # that they are not then followed by another digit
}x

关于regex - 正则表达式 - 连续 4 位数字,但不能全为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6311842/

相关文章:

javascript - 用于匹配两个其他字符串之间的字符串的正则表达式

Python使用正则表达式匹配具有多个换行符的段落

sql - 在 SSMS 对象资源管理器的过滤器设置中使用通配符/正则表达式来查找对象

python返回字符串的匹配和非匹配模式

regex - 为什么 "Year 2010"=~/([0-4]*)/导致 $1 中的空字符串?

html - 正则表达式 - 查找具有 name 属性但不具有 id 的元素

regex - 使用正则表达式替换 TextArea 中的文本会创建新行

java - 如何将 "string"转换为 "*s*t*r*i*n*g*"

android - 如何在android正则表达式中排除数字

正则表达式在 IntelliJ 中查找末尾没有换行符的文件