首页 > 解决方案 > Ruby:通过大写字母和首字母缩略词将字符串分解为单词

问题描述

我需要用大写字母和首字母缩略词将一个字符串分成几个字符串,我可以这样做:

myString.scan(/[A-Z][a-z]+/)

但它仅适用于大写字母,例如:

QuickFoxReadingPDF

或者

LazyDogASAPSleep

结果中缺少全大写的首字母缩略词。

我应该将 RegEx 更改为什么,或者有其他选择吗?

谢谢!

更新:

后来我发现我的一些数据有数字,比如“RabbitHole3”,如果解决方案可以考虑数字那就太好了,即。["Rabbit", "Hole3"].

标签: regexrubystringsplitacronym

解决方案


利用

s.split(/(?<=\p{Ll})(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/)

证明

解释

--------------------------------------------------------------------------------
  (?<=                     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"]


推荐阅读