Sök…


Anmärkningar

För att installera paket kör du helt enkelt:

install.packages("stringi")

att ladda det:

require("stringi")

Räkna mönster inuti strängen

Med fast mönster

stri_count_fixed("babab", "b")
# [1] 3
stri_count_fixed("babab", "ba")
# [1] 2
stri_count_fixed("babab", "bab")
# [1] 1

inbyggt:

length(gregexpr("b","babab")[[1]])
# [1] 3
length(gregexpr("ba","babab")[[1]])
# [1] 2
length(gregexpr("bab","babab")[[1]])
# [1] 1

funktionen är vektoriserad över sträng och mönster:

stri_count_fixed("babab", c("b","ba"))
# [1] 3 2
stri_count_fixed(c("babab","bbb","bca","abc"), c("b","ba"))
# [1] 3 0 1 0

En bas R-lösning :

sapply(c("b","ba"),function(x)length(gregexpr(x,"babab")[[1]]))
# b ba 
# 3  2

Med regex

Första exemplet - hitta a och alla tecken efter

Andra exemplet - hitta a och alla siffror efter

stri_count_regex("a1 b2 a3 b4 aa", "a.")
# [1] 3
stri_count_regex("a1 b2 a3 b4 aa", "a\\d")
# [1] 2

Duplicera strängar

stri_dup("abc",3)
# [1] "abcabcabc"

En bas R-lösning som gör samma sak ser så här ut:

paste0(rep("abc",3),collapse = "")
# [1] "abcabcabc"

Klistra in vektorer

stri_paste(LETTERS,"-", 1:13)
# [1] "A-1"  "B-2"  "C-3"  "D-4"  "E-5"  "F-6"  "G-7"  "H-8"  "I-9"  "J-10" "K-11" "L-12" "M-13" 
# [14] "N-1"  "O-2"  "P-3"  "Q-4"  "R-5"  "S-6"  "T-7"  "U-8"  "V-9"  "W-10" "X-11" "Y-12" "Z-13"

Naturligtvis kunde vi göra detta i R via:

> paste(LETTERS,1:13,sep="-")
 #[1] "A-1"  "B-2"  "C-3"  "D-4"  "E-5"  "F-6"  "G-7"  "H-8"  "I-9"  "J-10" "K-11" "L-12" "M-13"
 #[14] "N-1"  "O-2" "P-3"  "Q-4"  "R-5"  "S-6"  "T-7"  "U-8"  "V-9"  "W-10" "X-11" "Y-12" "Z-13"

Dela text efter något fast mönster

Delad vektor av texter med ett mönster:

stri_split_fixed(c("To be or not to be.", "This is very short sentence.")," ")
# [[1]]
# [1] "To"  "be"  "or"  "not" "to"  "be."
# 
# [[2]]
# [1] "This"      "is"        "very"      "short"     "sentence."

Dela upp en text med många mönster:

stri_split_fixed("Apples, oranges and pineaplles.",c(" ", ",", "s"))
# [[1]]
# [1] "Apples,"     "oranges"     "and"         "pineaplles."
# 
# [[2]]
# [1] "Apples"                   " oranges and pineaplles."
# 
# [[3]]
# [1] "Apple"          ", orange"       " and pineaplle" "."     


Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow