How to split a string into continuous one letter in R
2 answers
You can use the database R strsplit
with PCRE regular expression-based appeals .
s <- "aaehhhhhhhaannd"
strsplit(s, "(?<=(.))(?!\\1)", perl=TRUE)
# [[1]]
# [1] "aa" "e" "hhhhhhh" "aa" "nn" "d"
See the R demo online and the regex demo .
Regular Expression Details :
-
(?<=(.))
- a positive lookbehind ((?<=...)
) that "looks" to the left and commits any char to group 1 with a(.)
capturing group (this value can be traced from within the template using a\1
backreference ) -
(?!\\1)
- a negative result that does not match if there is the same value that was written to group 1 immediately to the right of the current location.
Since the images do not consume text, the separation occurs in the space between the different characters.
NOTE. If you want to .
match a newline, add (?s)
at the beginning of the pattern (as in PCRE regex, .
does not match a line break by default).
+2
source to share