2013-09-29 77 views
0

我希望將字符串拆分爲向量和列表。如果有OR||我想分成列表。如果有or & & split into a vector. With the word version I get it but not with the use of | and &`。下面是代碼:布爾正則表達式拆分

splitting <- function(x) { 
    lapply(strsplit(x, "OR|[\\|\\|]"), function(y){ 
     strsplit(y, "AND|[\\&\\&]") 
    }) 
} 

splitting("3AND4AND5OR4OR6AND7") ## desired outcome for all three 
splitting("3&&4&&5||4||6&&7") 
splitting("3&&4&&5OR4||6&&7") 

這裏是理想的結果:

> splitting("3AND4AND5OR4OR6AND7") 
[[1]] 
[[1]][[1]] 
[1] "3" "4" "5" 

[[1]][[2]] 
[1] "4" 

[[1]][[3]] 
[1] "6" "7" 

我怎樣才能恰當地設置這個正則表達式?我在做什麼不正確?

+0

請注意[R正則表達式是特定於R.如果沒有R的具體知識,請不要回應。 –

+0

雖然R正則表達式往往有點不同,但我認爲你應該能夠適應非R用戶的解決方案。只要確保將雙反斜槓反轉,如果它足夠複雜,請確保使用perl = TRUE。 – Dason

回答

1

我並不是說這是最好的答案,但如果您已經使用「AND」和「OR」解決了問題,那麼爲什麼不將它降低到您已經解決的問題呢?

splitting <- function(x) { 
    x <- gsub("&&", "AND", x, fixed = TRUE) 
    x <- gsub("||", "OR", x, fixed = TRUE) 

    lapply(strsplit(x, "OR|[\\|\\|]"), function(y){ 
    strsplit(y, "AND|[\\&\\&]") 
    }) 
} 

splitting("3AND4AND5OR4OR6AND7") ## desired outcome for all three 
splitting("3&&4&&5||4||6&&7") 
splitting("3&&4&&5OR4||6&&7") 

這只是突然出現在我的腦海的第一件事,我真的沒有想過,如果有更好的方式來做到這一點。

而且這似乎工作

splitting <- function(x) { 
    #x <- gsub("&&", "AND", x, fixed = T) 
    #x <- gsub("||", "OR", x, fixed = T) 

    lapply(strsplit(x, "OR|\\|\\|"), function(y){ 
    strsplit(y, "AND|\\&\\&") 
    }) 
} 
+0

謝謝我在想我必須用大括號將逃脫的角色分組,但實際上並不明智。謝謝。 +1 –