regex - strsplit 与 gregexpr 不一致

标签 regex r pcre strsplit

A comment关于我对 this question 的回答这应该使用 strsplit 给出所需的结果不会,即使它似乎正确匹配字符向量中的第一个和最后一个逗号。这可以使用 gregexpr 证明和 regmatches .

那么为什么strsplit在此示例中,在每个逗号上拆分,即使 regmatches只为同一个正则表达式返回两个匹配项?

#  We would like to split on the first comma and
#  the last comma (positions 4 and 13 in this string)
x <- "123,34,56,78,90"

#  Splits on every comma. Must be wrong.
strsplit( x , '^\\w+\\K,|,(?=\\w+$)' , perl = TRUE )[[1]]
#[1] "123" "34"  "56"  "78"  "90" 


#  Ok. Let's check the positions of matches for this regex
m <- gregexpr( '^\\w+\\K,|,(?=\\w+$)' , x , perl = TRUE )

# Matching positions are at
unlist(m)
[1]  4 13

#  And extracting them...
regmatches( x , m )
[[1]]
[1] "," ","

嗯?!到底是怎么回事?

最佳答案

@Aprillion 的理论是准确的,来自 R documentation :

The algorithm applied to each input string is


repeat {
    if the string is empty
        break.
    if there is a match
        add the string to the left of the match to the output.
        remove the match and all to the left of it.
    else
        add the string to the output.
        break.
}

换句话说,在每次迭代中 ^将匹配一个新字符串的开头(没有前面的项目。)

简单说明这种行为:
> x <- "12345"
> strsplit( x , "^." , perl = TRUE )
[[1]]
[1] "" "" "" "" ""

Here ,您可以使用前瞻断言作为分隔符来查看此行为的结果(感谢@JoshO'Brien 提供链接。)

关于regex - strsplit 与 gregexpr 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23969411/

相关文章:

javascript - 匹配所有javascript函数的正则表达式

ios - Swift 正则表达式函数更新

r - 如何在 st_intersect 之后从几何集合中选择某些几何图形?

r - 为什么 ggplot2 看到的 data.frame 和 data_frame 不同?

r - R 教程中的 Kohonen SOM 映射

php - 正则表达式模式获取花括号之间的字符串

sql - 正则表达式匹配除特定给定字符串之外的任何内容(包括空字符串)

regex - 如何在 perl 中将字符串的字母和数字分开?

Java:匹配城市正则表达式

regex - 在 powershell 中编辑特定符号之间的文本