为什么此正则表达式会在 2 位数字之间遗漏一个白色 space?

Why does this regex miss a single white space between 2 digits?

我试图在字符串中找到一个白色 space 并且两边各有一个数字。我构建了以下示例:

library('stringr')
str1 <- "1805.6 1-1 1"
str_locate_all(str1, "\s+")[[1]]
str_locate_all(str1, "[[:digit:]]\s[[:digit:]]")[[1]]

哪个 returns:

str_locate_all(str1, "\s+")[[1]]
     start end
[1,]     7   7
[2,]    11  11

str_locate_all(str1, "[[:digit:]]\s[[:digit:]]")[[1]]
     start end
[1,]     6   8
[2,]    10  12

这是我期望看到的。现在对不同的字符串执行相同的操作:

str2 <- "1805.6 1 1 1"
str_locate_all(str2, "\s+")[[1]]
str_locate_all(str2, "[[:digit:]]\s[[:digit:]]")[[1]]

但这似乎错过了被数字包围的 spaces 之一(请注意,第二个模式只有 returns 2 个条目):

str_locate_all(str2, "\s+")[[1]]
     start end
[1,]     7   7
[2,]     9   9
[3,]    11  11

str_locate_all(str2, "[[:digit:]]\s[[:digit:]]")[[1]]
     start end
[1,]     6   8
[2,]    10  12

那么问题来了,为什么第二个图案看不到中间的白色space和return与8 10的一行?我确定我只是没有从 regex 的思维方式中看到事情。

您在 space 之后的数字在比赛结束后被消耗。所以你无法找到匹配项。在你的例子中

注意:- x 表示匹配的数字

1805.6 1 1 1
     x^x
      |
   First match

1805.6 1 1 1
        ^
        |
Once the regex engine moves forward, it cannot see backward(unless lookbehind is used).
Here, first digit from regex is matched with space which is not correct so the match fails outright and next position is attempted.

1805.6 1 1 1    
         x^x
         ||Matches digit
         |Matches space
      Matches digit
     (Second match)

This goes on till end of string is reached

在这里可视化

您可以使用 lookahead 代替

> str_locate_all(str1, "\d\s(?=\d)")[[1]]
     start end
[1,]     6   7
[2,]     8   9
[3,]    10  11

由于 lookaheads 的宽度为零,我们得到的位置比实际结束位置小一位。