2

How do I replace an all caps string with the corresponding pascal case version? For example, If I have these strings:

SOMETHING_COOL SOMETHING_LESS_COOL WHATEV

I want this output:

SomethingCool SomethingLessCool Whatev

I got this far with the regex:

^*public\s[\w-]+?(\?)?\s[A-Z]+?(_[A-Z]+)?(_[A-Z]+)? { get; set; }

...which I think works for all cases I need. The real question is how to replace the matches with the corresponding pascal case.

EDIT: I will be using .NET/C# looking at files

Noel
  • 3,288
  • 1
  • 23
  • 42

2 Answers2

1

for the pascal casing of the identifier once you have matched it, you can use another regex.

I've changed your original regex so it uses looking forward and backwards to only capture the identifier as the match

This code takes some C# code with your funky naming scheme and replaces it with code with pascal casing :-

var code = "public class Blah\r\n   public int SOMETHING_LESS_COOL { get; set; }\r\n }";
var identifierRegex = new Regex(@"(?<=^\s*public\s[\w-]+?(\?)?\s)[A-Z]+(_[A-Z]+)*(?=\s*\{\s*get;\s*set;\s*\})", RegexOptions.Multiline);           
var underscoreRegex = new Regex(@"(_|\s|^)\w");           
var pascalCode = identifierRegex.Replace(code, 
       i => underscoreRegex.Replace(i.Value.ToLower(),
                          m => m.Value.ToUpper().Replace("_",""))); 

While this will change the declarations, it won't replace any code that uses those properties. So you'd be left with a fair bit of cleanup work. Might be interesting to see if you can script visual studio to do "Rename" refactorings.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • If you are using `var` then you are using the code in-line. If you are using the code in-line you probability shouldn't use `RegexOptions.Compiled`. See this [this question and answer](http://stackoverflow.com/questions/513412/how-does-regexoptions-compiled-work) for some performance numbers – Scott Chamberlain Jun 20 '13 at 23:08
  • @ScottChamberlain sure, but if he builds this into a class I'd more expect the regexs to be setup beforehand and then he'd iterate through his files doing the replaces... – Keith Nicholas Jun 20 '13 at 23:11
  • @ScottChamberlain took them out for the snippet... helps reduce the code clutter a bit! – Keith Nicholas Jun 20 '13 at 23:16
0

Having an identifier in a string variable, try the following:

var parts = identifier.Split('_');
var pascalCasedParts = parts.Select(p => p[0] +
                           new string(p.ToLower().Skip(1).ToArray()));
var pascalIdent = string.Join("", pascalCasedParts.ToArray());
Vlad
  • 35,022
  • 6
  • 77
  • 199