问题描述
我需要用大写字母和首字母缩写词将一个字符串分成几个字符串,我可以这样做:
myString.scan(/[A-Z][a-z]+/)
但是它仅适用于大写字母,例如:
QuickFoxReadingPDF
或
LazyDogASAPSleep
结果中缺少全字母缩写词。
我应该将RegEx更改为什么,或者有其他选择吗?
谢谢!
更新:
后来我发现我的一些数据有数字,例如“ RabbitHole3”,如果解决方案可以考虑数字,那就太好了。 ["Rabbit","Hole3"]
。
解决方法
使用
s.split(/(?<=\p{Ll})(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/)
请参见proof。
说明
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
\p{Ll} any lowercase letter
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\p{Lu} any uppercase letter
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
\p{Lu} any uppercase letter
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\p{Lu}\p{Ll} any uppercase letter,any lowercase letter
--------------------------------------------------------------------------------
) end of look-ahead
str = 'QuickFoxReadingPDF'
p str.split(/(?<=\p{Ll})(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/)
结果:["Quick","Fox","Reading","PDF"]
模式[A-Z][a-z]+
与单个大写字符A-Z和一个或多个小写字符a-z匹配,后者不考虑多个大写字符。
在这种情况下,当大写字符不紧跟小写字符a-z
时,您还想匹配大写字符。
不确定首字母缩写是否可以包含一个大写字符,但是是否应该至少有2个大写字符
[A-Z][a-z]+|[A-Z]{2,}(?![a-z])