RegEx用于在大写字母之前添加下划线 [英] RegEx for adding underscore before capitalized letters

查看:438
本文介绍了RegEx用于在大写字母之前添加下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在字符串的大写字母之前添加下划线(_),但第一个字母除外?

How do I add underscore (_) before capitalized letters in a string, excepted the first one ?

[1] "VarLengthMean" "VarWidthMean" 

我希望它成为:

[1] "Var_Length_Mean" "Var_Width_Mean" 

我考虑过使用stringr中的str_replace_all,但是我不知道应该使用哪个正则表达式.

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\\2)捕获的组

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"


如果还有更多实例,请使用gsub

gsub("(?<=[a-z])(?=[A-Z])", "_", v2,  perl = TRUE)
#[1] "Var_Length_Mean" "Var_Width_Mean" 

数据

v1 <- c("VarLength", "VarWidth" )
v2 <- c("VarLengthMean", "VarWidthMean")

这篇关于RegEx用于在大写字母之前添加下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆