tags:

views:

60

answers:

5

Hello,

i need to replace upper case letter in variable name with lower case letter and add space

For example:

"NotImplementedException" should be "Not implemented exception" "UnhandledException" should be "Unhandled exception"

Thanks

+1  A: 

This is not something that can be done with plain regular expressions. While some regex engines may support lowercasing text, you will probably need to use a callback to process the matches.

Ignacio Vazquez-Abrams
A: 

What language are you using? regex may not be necessary (and even though it may be the best way to match a string, you'll probably need a function to do the work of replacing the text). Also regex syntax has many variants across different languages.

fearoffours
+3  A: 

Since you did not specify a language, I'll give an example in C#. I am sure your language will offer something like it.

String s = "NotImplementedException";
s = Regex.Replace(s, @"\B[A-Z]", (Match m) => " " + m.ToString().ToLower());
// s = "Not implemented exception"
Jens
A: 

@Ignacio, I beg to differ. Certainly this is not something which can be done in one statement with plain regular expressions. But the sed command:

sed -e 's/\([a-zA-Z]\)C/\1 c/g' infile.txt

will replace all occurrences of 'C' with ' c' when the 'C' is immediately preceded by a letter. All OP has to do is make 26 variants of this, which might be tedious. And getting the condition under which the case is altered might be difficult too but that's always the case with using regular expressions for global search-and-replace.

High Performance Mark
+1  A: 

It can be done in sed with single command:

$ echo "NotImplementedException" | sed 's/\B[A-Z]/ \l&/g'
Not implemented exception

But support for \l (and \u, \L, \U and \E) is rare among Regex implementations in different languages. I'm only sure that Perl has this implemented.

Rorick