我正在寻找一种只能使用正则表达式完成的解决方案。我知道这对于变量、子字符串等很容易。
即使我提到了 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/