29

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.

0

4 Answers 4

31

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
5
  • +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. Mar 12, 2012 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, 2012 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? Mar 12, 2012 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, 2012 at 16:18
  • 1
    Thanks a lot for this answer. You stand next to Jesus in my book. Jun 27, 2013 at 1:06
5

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'
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.