Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is CamelCase conversion?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.

What is CamelCase in C?

CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces. It is commonly used in web URLs, programming and computer naming conventions. It is named after camels because the capital letters resemble the humps on a camel's back.


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

Uppercases letters following _-:

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

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'

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