首页 > 解决方案 > 如何使用 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的变量具有我上面提到的完整文件路径。我在这里做错了什么?

标签: regexrubystring

解决方案


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

推荐阅读