开发者

How to replace upper case with lower case using regex?

I need to replace upper case letter in variable name with lower c开发者_运维百科ase letter and add space

For example:

NotImplementedException should be Not implemented exception UnhandledException should be Unhandled exception


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]", m => " " + m.ToString().ToLower());
// s = "Not implemented exception"


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.


@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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜