regex - 如何使用 Ruby 正则表达式返回字符串的第一个匹配子字符串?
问题描述
我正在寻找一种在 Ruby 中对字符串执行正则表达式匹配并获取第一个匹配子字符串并分配给变量的方法。我在堆栈溢出中检查了不同的解决方案,但到目前为止找不到合适的解决方案。
这是我的字符串
/usr/share/filebeat/reports/ui/local/20200904_151507/API/API_Test_suite/20200904_151508/20200904_151508.csv
我需要获取20200904_151507
. 好吧,这个文件路径可以不时改变。还有子字符串。但模式是,date_time
。在下面的正则表达式中,我尝试获取前八 (8) 个数字、_ 和后六 (6) 个数字。这是我尝试过的解决方案,
report_path[/^[0-9]{8}[_][0-9]{6}$/,1]
report_path.scan(/^[0-9]{8}[_][0-9]{6}$/).first
上面report_path
的变量具有我上面提到的完整文件路径。我在这里做错了什么?
解决方案
scan
将返回与模式匹配的所有子字符串。您可以使用match
,scan
或[]
来实现您的目标:
report_path = '/usr/share/filebeat/reports/ui/local/20200904_151507/API/API_Test_suite/20200904_151508/20200904_151508.csv'
report_path.match(/\d{8}_\d{6}/)[0]
# => "20200904_151507"
report_path.scan(/\d{8}_\d{6}/)[0]
# => "20200904_151507"
# String#[] supports regex
report_path[/\d{8}_\d{6}/]
# => "20200904_151507"
请注意,它match
返回一个MatchData
对象,其中可能包含多个匹配项(如果我们使用捕获组)。scan
将返回一个Array
包含所有匹配项。
在这里,我们呼吁[0]
获得MatchData
第一场比赛
捕获组:
正则表达式允许我们使用一种模式捕获多个子字符串。我们可以()
用来创建捕获组。(?'some_name'<pattern>)
允许我们创建命名的捕获组。
report_path = '/usr/share/filebeat/reports/ui/local/20200904_151507/API/API_Test_suite/20200904_151508/20200904_151508.csv'
matches = report_path.match(/(\d{8})_(\d{6})/)
matches[0] #=> "20200904_151507"
matches[1] #=> "20200904"
matches[2] #=> "151507"
matches = report_path.match(/(?'date'\d{8})_(?'id'\d{6})/)
matches[0] #=> "20200904_151507"
matches["date"] #=> "20200904"
matches["id"] #=> "151507"
我们甚至可以使用(命名的)捕获组[]
从String#[]
文档:
如果提供了 Regexp,则返回字符串的匹配部分。如果捕获遵循正则表达式(可能是捕获组索引或名称),则遵循返回 MatchData 组件的正则表达式。
report_path = '/usr/share/filebeat/reports/ui/local/20200904_151507/API/API_Test_suite/20200904_151508/20200904_151508.csv'
# returns the full match if no second parameter is passed
report_path[/(\d{8})_(\d{6})/]
# => 20200904_151507
# returns the capture group n°2
report_path[/(\d{8})_(\d{6})/, 2]
# => 151507
# returns the capture group called "date"
report_path[/(?'date'\d{8})_(?'id'\d{6})/, 'date']
# => 20200904
推荐阅读
- windows - 为什么它说“'flutter'不被识别为内部或外部命令”即使我为flutter设置了正确的PATH变量
- google-apps-script - 如果来自 Google 表单的传入行中的单元格具有特定值,则运行脚本函数
- linux - 以编程方式使用 perf 列表中的 perf 事件
- vhdl - 调试:VHDL 错误案例语句未涵盖所有选择。需要“其他”子句,但定义了所有状态
- python - 这个程序一次又一次地给出答案,我找不到阻止它的方法
- shopify - 突出显示 shopify 中的活动收藏按钮
- c# - 在接口内部的上下文中,“新”运算符是什么意思?
- ios - 更改 Xcode 11 后未找到架构 x86_64 的符号
- java - System.err.print(ln) 与 system.out.println 在同一行吗?JAVA
- python - 把Python的输入函数变成C