RegEx for adding underscore before capitalized letters

瘦欲@ 提交于 2019-12-07 15:32:51

问题


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?


回答1:


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")



回答2:


If your language supports assertions, this is all you need

Find (?<=[a-z])(?=[A-Z])
Replace _




回答3:


Or:

str_replace_all(v, "\\B([A-Z]+)", "_\\1")


来源:https://stackoverflow.com/questions/56131210/regex-for-adding-underscore-before-capitalized-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!