使用正则表达式拆分CamelCase [英] Splitting CamelCase with regex
本文介绍了使用正则表达式拆分CamelCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码可通过正则表达式拆分CamelCase:
I have this code to split CamelCase by regular expression:
Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled).Trim();
但是,它不能正确拆分: ShowXYZColours
However, it doesn't split this correctly: ShowXYZColours
它产生 Show XYZColours
而不是 Show XYZ Colours
如何获得所需的结果?
推荐答案
支持Unicode的
(?=\p{Lu}\p{Ll})|(?<=\p{Ll})(?=\p{Lu})
故障:
(?= # look-ahead: a position followed by...
\p{Lu}\p{Ll} # an uppercase and a lowercase
) #
| # or
(?<= # look-behind: a position after...
\p{Ll} # an uppercase
) #
(?= # look-ahead: a position followed by...
\p{Lu} # a lowercase
) #
与正则表达式拆分功能一起使用.
Use with your regex split function.
当然,您可以将 \ p {Lu}
替换为 [AZ]
,将 \ p {Ll}
替换为[az]
,如果这是您所需要的,或者您的正则表达式引擎不了解Unicode类别.
Of course you can replace \p{Lu}
with [A-Z]
and \p{Ll}
with [a-z]
if that's what you need or your regex engine does not understand Unicode categories.
这篇关于使用正则表达式拆分CamelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文