Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use regular expressions to camelize/underscore strings?

Is it possible to use nothing but Regular Expressions to convert strings like "hello_world" into "HelloWorld" and back?

I'm asking because I often need to create snippets for Sublime Text that automatically fills in "class_name" somewhere when I type "ClassName" somewhere else. I can only use perl-style regular expressions for this purpose.

like image 849
Hubro Avatar asked Jun 26 '13 11:06

Hubro


People also ask

Is underscore a regular expression?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).

Do you need to escape underscore in regex?

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

Which string methods are used with regular expression?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() .

Can regex be a string?

In formal language theory, a regular expression (a.k.a. regex, regexp, or r.e.), is a string that represents a regular (type-3) language. Huh?? Okay, in many programming languages, a regular expression is a pattern that matches strings or pieces of strings.


1 Answers

Using perl regular expression:

hello_world -> HelloWorld

s/(_|\b)([a-z])/\u\2/g;
  • \b: Match at boundary (space, start of string, punctuation mark, ..)
  • [a-z]: lowercase alphabet
  • \u: make uppercase for next character
  • \2: group 2 (first lowercase character)
  • (_|\b) -> group 1
  • ([a-z]) -> group2

HelloWorld -> hello_world

s/([A-Z][a-z]+|[a-z]+)([A-Z])/\l\1_\l\2/g;
  • Does not work for Hello.
  • If you can use two substitutions, use s/([A-Z])/_\l\1/g; followed by s/^_//;
like image 153
falsetru Avatar answered Sep 30 '22 15:09

falsetru