RegEx for adding underscore before capitalized letters

若如初见. 提交于 2019-12-06 01:34:33
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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!