3 回答

TA貢獻1799條經(jīng)驗 獲得超9個贊
我不確定是否將其視為錯誤,因為我認為這是基于R文檔的預期行為。來自?strsplit:
應用于每個輸入字符串的算法是
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.
}
請注意,這意味著,如果(非空)字符串的開頭存在匹配項,則輸出的第一個元素為““””,但是如果字符串的末尾存在匹配項,則輸出為與刪除匹配項相同。
問題在于,向前(和向后)斷言的長度為零。因此,在這種情況下,例如:
FF <- "(?=funky)"
testString <- "take me to funky town"
gregexpr(FF,testString,perl=TRUE)
# [[1]]
# [1] 12
# attr(,"match.length")
# [1] 0
# attr(,"useBytes")
# [1] TRUE
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "take me to " "f" "unky town"
發(fā)生的情況是,孤獨的超前(?=funky)位置在位置12處匹配。因此,第一個拆分包括直到位置11(匹配項的左側)的字符串,并將其與匹配項一起從字符串中刪除,但匹配項的長度為零。
現(xiàn)在剩下的字符串是funky town,并且前行在位置1處匹配。但是,沒有什么要刪除的,因為在匹配項的左側沒有任何內(nèi)容,并且匹配項的長度為零。因此,算法陷入了無限循環(huán)。顯然,R通過拆分單個字符來解決此問題,順便說一下,這是strsplit使用空的正則表達式(當參數(shù)為ing時split="")所記錄的行為。在此之后,剩下的字符串是unky town,由于沒有匹配項,因此將作為最后一個拆分返回。
Lookbehinds沒問題,因為每個匹配項都被拆分并從剩余的字符串中刪除,因此算法永遠不會卡住。
乍一看,這種行為看起來很奇怪。但是,否則,行為將違背前瞻零長度的假設。鑒于strsplit已記錄了該算法,我相信這不符合錯誤的定義。

TA貢獻1817條經(jīng)驗 獲得超14個贊
基于Theodore Lytras對substr()行為的仔細說明,一種合理的解決方法是在待匹配的超前斷言前面加上一個與任何單個字符匹配的肯定后向斷言:
testString <- "take me to funky town"
FF2 <- "(?<=.)(?=funky)"
strsplit(testString, FF2, perl=TRUE)
# [[1]]
# [1] "take me to " "funky town"

TA貢獻1111條經(jīng)驗 獲得超0個贊
對我來說似乎是個蟲子。具體來說,這似乎不僅僅與空格有關,而是任何孤獨的超前行為(正數(shù)或負數(shù)):
FF <- "(?=funky)"
testString <- "take me to funky town"
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "take me to " "f" "unky town"
FF <- "(?=funky)"
testString <- "funky take me to funky funky town"
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "f" "unky take me to " "f" "unky "
# [5] "f" "unky town"
FF <- "(?!y)"
testString <- "xxxyxxxxxxx"
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "xxx" "y" "xxxxxxx"
如果給出一些要捕獲的內(nèi)容以及零寬度斷言,則似乎可以正常工作,例如:
FF <- " (?=XX )"
testString <- "text XX text"
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "text" "XX text"
FF <- "(?= XX ) "
testString <- "text XX text"
strsplit(testString,FF,perl=TRUE)
# [[1]]
# [1] "text" "XX text"
也許類似的東西可以作為解決方法。
- 3 回答
- 0 關注
- 749 瀏覽
添加回答
舉報