我正在寻找一种对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
以上的变量具有我上面提到的完整文件路径。
我在这里做错了什么?
答案 0 :(得分:0)
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
以获得第一场比赛
捕获组:
Regex允许我们使用一种模式捕获多个子串。我们可以使用()
创建捕获组。 (?'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