2012-03-15 60 views
2

我有几个短语列表按照以下格式正则表达式如何分割这个单词?

thisIsAnExampleSentance 
hereIsAnotherExampleWithMoreWordsInIt 

,我试图用

This Is An Example Sentance 
Here Is Another Example With More Words In It 

每个短语落得有白色空间凝结和第一字母被强制为小写字母

我可以使用regexA-Z前添加一个空格,有这句话的第一个字母是大写

我认为做这样的事情

([a-z]+)([A-Z])([a-z]+)([A-Z])([a-z]+) // etc 
$1 $2$3 $4$5 // etc 

,但对50条记录的不同长度,我的想法是一个贫穷的解决方案。有没有办法regex的方式,将更多动态谢谢

+2

什么语言是你使用? – xanatos 2012-03-15 19:33:17

+0

迭代字符串并在每个大写字母前添加空格可能更容易。 – Ilion 2012-03-15 19:37:48

+0

like([a-z] +)+(([A-Z])([a-z] +))*?那样有用吗? – Colleen 2012-03-15 19:39:06

回答

1

对于空间的问题很容易,如果你的语言支持零宽度向后看

var result = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "(?<=[a-z])([A-Z])", " $1"); 

或者即使它不支持

var result2 = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "([a-z])([A-Z])", "$1 $2"); 

我使用C#,但正则表达式应该可以在支持替换的任何语言中使用,使用$1 ... $n

但是对于低位到高位的情况,您不能直接在正则表达式中执行。你可以通过一个正则表达式得到第一个字符,如:^[a-z],但你不能把它转化。

例如在C#中,你可以使用一个匹配评估,以改变输入字符串做

var result4 = Regex.Replace(result, "^([a-z])", m => 
{ 
    return m.ToString().ToUpperInvariant(); 
}); 

然后,您可以甚至融合两个一起

var result4 = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "^([a-z])|([a-z])([A-Z])", m => 
{ 
    if (m.Groups[1].Success) 
    { 
     return m.ToString().ToUpperInvariant(); 
    } 
    else 
    { 
     return m.Groups[2].ToString() + " " + m.Groups[3].ToString(); 
    } 
}); 
我用
+0

好吧,你可以用一个perl正则表达式(在替换表达式中使用'\ U'约定 - 请参阅@ Qtax的答案,但这可能不适用,因为我们不知道什么语言或工具是正在使用 – 2012-03-15 21:35:49

2

一个Java片段看起来是这样的(现在的修订版):

result = source.replaceAll("(?<=^|[a-z])([A-Z])|([A-Z])(?=[a-z])", " $1$2"); 
result = result.substring(0, 1).toUpperCase() + result.substring(1); 

这,顺便说一句,串givenProductUPCSymbol转换成Given Product UPC Symbol - 确保您使用这种类型的东西的方式很好

最后,单行版本可能是:

result = source.substring(0, 1).toUpperCase() + source(1).replaceAll("(?<=^|[a-z])([A-Z])|([A-Z])(?=[a-z])", " $1$2"); 

此外,类似于一个在问题的评论给出的例子,该字符串hiMyNameIsBobAndIWantAPuppy将改为Hi My Name Is Bob And I Want A Puppy

1

一个Perl例如使用Unicode字符支持:

s/\p{Lu}/ $&/g; 
s/^./\U$&/;