ruby - Ruby regex 获取由句点分隔的单词组合
问题描述
我正在尝试使用 Ruby 正则表达式来获得如下所示的单词组合。在下面的示例中,我只需要案例 1-4,* 将它们标记为大写以便于测试。中间的单词 ( dbo, bcd
) 可以是与 case#3 类似的任何内容或任何内容。我很难让那个双周期案例#3 工作。也可以SALES
作为单词独立使用,但对于一个正则表达式 ?Tx all guru 来说可能太多了。这是我部分工作的脚本,需要添加alpha..SALES
s = '1 alpha.dbo.SALES 2 alpha.bcd.SALES 3 alpha..SALES 4 SALES
bad cases 5x alpha.saleS 6x saleSXX'
regex = /alpha+\.+[a-z]+\.?sales/ix
puts 'R: ' + s.scan(regex).to_s
##R: ["alpha.dbo.SALES", "alpha.bcd.SALES"]
解决方案
r = /
(?<=\d[ ]) # match a digit followed by a space in a positive lookbehind
(?: # begin a non-capture group
\p{Alpha}+ # match one or more letters
\. # match a period
(?: # begin a non-capture group
\p{Alpha}+ # match one or more letters
\. # match a period
| # or
\. # match a period
) # end non-capture group
)? # end non-capture group and optionally match it
SALES # match string
(?!=[.\p{Alpha}]) # do not match a period or letter (negative lookahead)
/x # free-spacing regex definition mode.
s.scan(r)
#=> ["alpha.dbo.SALES", "alpha.bcd.SALES", "alpha..SALES", "SALES"]
这个正则表达式习惯上写成如下。
r = /
(?<=\d )(?:\p{Alpha}+\.(?:\p{Alpha}+\.|\.))?SALES(?!=[.\p{Alpha}])/
在自由间距模式下,空格必须放在字符类 ( [ ]
) 中;否则它将被剥离。
推荐阅读
- axapta - 在 AX 2012 x++ 中创建常规日记帐时刷新固定资产的价值模型
- html - Bootstrap 4 间距
- python - 为什么我在绘制饼图时遇到问题?
- python - Python:如何将函数结果输出到数据框
- c - dev c++和在线编译器有什么区别?
- java - [ConcurrentHashMap]:地图更新/获取操作在单线程操作中从地图返回陈旧值
- wso2is - Wso2身份服务器i18n关闭编码HTML?
- angular - 无法在垫卡列表上添加水平滚动
- android - 我们应该在 Android 中使用 getPath 还是 getAbsolutePath
- python - 如何解析 mitmdump 文件?