28

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.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

4 Answers4

30

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
Qtax
  • 33,241
  • 9
  • 83
  • 121
  • +1: Neat. About the only possible quibble is that `_tea_break` would become `TeaBreak` rather than `teaBreak` or `_teaBreak`. But that would serve someone right for using names starting with an underscore. – Jonathan Leffler Mar 12 '12 at 15:38
  • @JonathanLeffler, you're right, and there would also be problems if multiple consecutive underscores were used. Updated the answer to fix that. – Qtax Mar 12 '12 at 15:49
  • 1
    Thanks, but because this is for use in editor search and replace dialogs I was asking to do this using a single regex. `$_ = lc` breaks this constraint. Can you think of a way to combine them? – Jeff Axelrod Mar 12 '12 at 15:50
  • @glenviewjeff, the `lc` less solution didn't work right for names like `var_x_short`, updated and fixed now. – Qtax Mar 12 '12 at 16:18
  • 1
    Thanks a lot for this answer. You stand next to Jesus in my book. – gran_profaci Jun 27 '13 at 01:06
4

Uppercases letters following _-:

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

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'
jbohren
  • 576
  • 4
  • 5
1

I prefer user846969's answer but somehow it was not finding other matches in the tool that is using EBNF (extended Backus-Naur form). Here is somthing that worked for me:

/(?:([a-z0-9]*)[_-])([a-z])/${1}${2:/upcase}/g
jaques-sam
  • 2,578
  • 1
  • 26
  • 24