How do I add underscore (_) before capitalized letters in a string, excepted the first one ?
[1] "VarLengthMean" "VarWidthMean"
I want it to become :
[1] "Var_Length_Mean" "Var_Width_Mean"
I considered using str_replace_all
from stringr
, but I can't figure out which regexp I should use.
How do I solve this problem?
akrun
One option would be to capture the lower case letter and the following upper case letter, and then insert the _
while adding the backreference (\\1
, \\2
) of the captured group
sub("([a-z])([A-Z])", "\\1_\\2", v1)
#[1] "Var_Length" "Var_Width"
If there are more instances, use gsub
gsub("(?<=[a-z])(?=[A-Z])", "_", v2, perl = TRUE)
#[1] "Var_Length_Mean" "Var_Width_Mean"
data
v1 <- c("VarLength", "VarWidth" )
v2 <- c("VarLengthMean", "VarWidthMean")
If your language supports assertions, this is all you need
Find (?<=[a-z])(?=[A-Z])
Replace _
Or:
str_replace_all(v, "\\B([A-Z]+)", "_\\1")
来源:https://stackoverflow.com/questions/56131210/regex-for-adding-underscore-before-capitalized-letters