Haezer
Haezer

Reputation: 476

RegEx for adding underscore before capitalized letters

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?

Upvotes: 2

Views: 833

Answers (3)

user557597
user557597

Reputation:

If your language supports assertions, this is all you need

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

Upvotes: 0

r.user.05apr
r.user.05apr

Reputation: 5456

Or:

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

Upvotes: 0

akrun
akrun

Reputation: 887571

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

Upvotes: 5

Related Questions