Regex 为什么这个正则表达式在两个数字之间遗漏了一个空格?

Regex 为什么这个正则表达式在两个数字之间遗漏了一个空格?,regex,r,stringr,Regex,R,Stringr,我试图找到一个单独的空白,在字符串的每一边都有一个数字。我构建了以下示例: library('stringr') str1 <- "1805.6 1-1 1" str_locate_all(str1, "\\s+")[[1]] str_locate_all(str1, "[[:digit:]]\\s[[:digit:]]")[[1]] 这就是我期望看到的。现在对不同的字符串执行相同的操作: str2 <- "1805.6 1 1 1" str_locate_all(str2, "\

我试图找到一个单独的空白,在字符串的每一边都有一个数字。我构建了以下示例:

library('stringr')
str1 <- "1805.6 1-1 1"
str_locate_all(str1, "\\s+")[[1]]
str_locate_all(str1, "[[:digit:]]\\s[[:digit:]]")[[1]]
这就是我期望看到的。现在对不同的字符串执行相同的操作:

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

所以问题是,为什么第二个模式没有看到中间的空白,并返回一行
8 10
?我敢肯定,我只是没有从
regex
的思维方式中看到问题。

比赛结束后,你的数字空间被消耗掉了。因此,您无法找到匹配项。在你的例子中

注:-
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的宽度为零,我们得到的位置比实际结束位置小一个。

匹配项被消耗。尝试搜索重叠的正则表达式我发现这个输出很有趣,尽管
str\u locate\u all(str2,“(?=(\\d\\s\\d))”)[[1]
结尾在开头之前:)感谢您的清晰解释。相关问题:使用
[[:digit:]
\\d
之间是否存在功能上的差异?谢谢。@BryanHanson不,我不这么认为(直到我知道)…我观察到的一件事是,
[:digit:][]
主要由DFA engineThanks支持。它在我的备忘单上,所以我用了它。以后我会用简短的形式。
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
> str_locate_all(str1, "\\d\\s(?=\\d)")[[1]]
     start end
[1,]     6   7
[2,]     8   9
[3,]    10  11