How can I convert from underscores to camel case with a regex?

假如想象 提交于 2019-12-30 05:38:09

问题


How can I convert names with underscores into camel case names as follows using a single Java/Perl regular expression search and replace?

underscore_variable_name -> underscoreVariableName
UNDERSCORE_VARIABLE_NAME -> underscoreVariableName
_LEADING_UNDERSCORE -> leadingUnderscore

The reason I ask for a single regular expressions is that I want to do this using Eclipse or Notepad++ search and replace.


回答1:


Some Perl examples:

my $str = 'variable_name, VARIABLE_NAME, _var_x_short,  __variable__name___';

### solution 1
$_ = $str;

$_ = lc;
s/_(\w)/\U$1/g;

say;

### solution 2: multi/leading underscore fix
$_ = $str;

$_ = lc;
s/(?<=[^\W_])_+([^\W_])|_+/\U$1/g;

say;

### solution 3: without prior lc
$_ = $str;

s/(?<=[^\W_])_+([^\W_])|([^\W_]+)|_+/\U$1\L$2/g;

say;

Output:

variableName, variableName, VarXShort,  _variable_name__
variableName, variableName, varXShort,  variableName
variableName, variableName, varXShort,  variableName



回答2:


Uppercases letters following _-:

s/[_-]([a-z])/\u$1/gr



回答3:


If you already have camelCase variables in the string, then @Qtax's answer will make them lowercase. If all of your variables are lower-case under_scored then you can make the following modification to #3: W --> A-Z

's/(?<=[^\A-Z_])_+([^\A-Z_])|([^\A-Z_]+)|_+/\U$1\L$2/g'


来源:https://stackoverflow.com/questions/9669703/how-can-i-convert-from-underscores-to-camel-case-with-a-regex

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