regex - Ruby:通过大写字母和首字母缩略词将字符串分解为单词
问题描述
我需要用大写字母和首字母缩略词将一个字符串分成几个字符串,我可以这样做:
myString.scan(/[A-Z][a-z]+/)
但它仅适用于大写字母,例如:
QuickFoxReadingPDF
或者
LazyDogASAPSleep
结果中缺少全大写的首字母缩略词。
我应该将 RegEx 更改为什么,或者有其他选择吗?
谢谢!
更新:
后来我发现我的一些数据有数字,比如“RabbitHole3”,如果解决方案可以考虑数字那就太好了,即。["Rabbit", "Hole3"]
.
解决方案
利用
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"]
推荐阅读
- node.js - nodejs中的异步构造函数
- mysql - Ansible playbook 在尝试执行 mysql 操作时卡住了
- java - 需要使用 if/else 语句在 For 循环中返回两个值
- python - 不断收到 django.db.utils.ProgrammingError: no results to fetch when running more than 4 processes
- python - 获取第三级或第四级 JSON 密钥的值
- python - 无法将表单字段设为只读
- python - Scipy peak_widths返回TypeError:只有整数标量数组可以转换为标量索引
- python - 在matplotlib中,如果一个刻度标签太长,如何约束长度并让它显示为多行?
- reactjs - React 组件在最终调度和 redux 状态更新时未更新
- android - 如何在使用 QR 配置设备时添加特定系统应用程序