Splitting CamelCase with regex

前端 未结 4 710
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 20:18

I have this code to split CamelCase by regular expression:

Regex.Replace(input, \"(?<=[a-z])([A-Z])\", \" $1\", RegexOptions.Compiled).Trim();
         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-11 21:02

    using Tomalak's regex with .NET System.Text.RegularExpressions creates an empty entry in position 0 of the resulting array:

    Regex.Split("ShowXYZColors", @"(?=\p{Lu}\p{Ll})|(?<=\p{Ll})(?=\p{Lu})")
    
    {string[4]}
        [0]: ""
        [1]: "Show"
        [2]: "XYZ"
        [3]: "Colors"
    

    It works for caMelCase though (as opposed to PascalCase):

    Regex.Split("showXYZColors", @"(?=\p{Lu}\p{Ll})|(?<=\p{Ll})(?=\p{Lu})")
    
    {string[3]}
        [0]: "show"
        [1]: "XYZ"
        [2]: "Colors"
    

提交回复
热议问题