Ruby通过正则表达式提取字符串

问题描述 投票:0回答:5

我有这些字符串:

'da_report/GY4LFDN6/2017_11/view_mission_join_player_count2017_11/index.html'
'da_report/GY4LFDN6/2017_11/activily_time2017_11/index.html'

从这两个字符串中,我想提取这两个文件名:

'2017_11/view_mission_join_player_count2017_11'
'2017_11/activily_time2017_11'

我写了一些正则表达式,但它们似乎错了。

str = 'da_report/GY4LFDN6/2017_11/view_mission_join_player_count2017_11/index.html'
str[/([^\/index.html]+)/, 1] # => "a_r"
ruby regex
5个回答
1
投票

正则表达式在这里是一种矫枉过正,我容易出错。

input = [
  "da_report/GY4LFDN6/" \
  "2017_11/view_mission_join_player_count2017_11" \
  "/index.html",
  "da_report/GY4LFDN6/" \
  "2017_11/activily_time2017_11" \
  "/index.html"
]  

input.map { |str| str.split('/')[2..3].join('/') }
#⇒ [
#   [0] "2017_11/view_mission_join_player_count2017_11",
#   [1] "2017_11/activily_time2017_11"
# ]

或者,更优雅:

input.map { |str| str.split('/').grep(/2017_/).join('/') }

0
投票

使用/(?<=GY4LFDN6\/)(.*)(?=\/index.html)/

str = 'da_report/GY4LFDN6/2017_11/view_mission_join_player_count2017_11/index.html'
str[/(?<=GY4LFDN6\/)(.*)(?=\/index.html)/]
 => "2017_11/view_mission_join_player_count2017_11"

现场演示:http://rubular.com/r/Ued6UOXWDf


0
投票

这个答案假定您希望从路径的第三个组件开始捕获,直到并包括文件名之前的路径的最后一个组件。如果是这样,那么我们可以使用以下正则表达式模式:

(?:[^/]*/){2}(.*)/.*

括号中的数量是捕获组,即您要从整个路径中提取的内容。

str = 'da_report/GY4LFDN6/2017_11/view_mission_join_player_count2017_11/index.html'
puts str[/(?:[^\/]*\/){2}(.*)\/.*/, 1]

Demo


0
投票

如果您要查找字符串末尾的值,例如string/string格式,后跟/filename.extension格式,则可以使用正向前瞻作为文件名。

\w+\/\w+(?=\/\w+\.\w+$)

Demo


0
投票

根据您的示例,您可以使用非常简单的正则表达式。

def extract(str)
  str[/\d{4}_\d{2}.+\d{4}_\d{2}/]
end

extract 'da_report/GY4LFDN6/2017_11/view_mission_join_player_count2017_11/index.html'
  #=> "2017_11/view_mission_join_player_count2017_11"
extract 'da_report/GY4LFDN6/2017_11/activily_time2017_11/index.html'
  #=> "2017_11/activily_time2017_11"
© www.soinside.com 2019 - 2024. All rights reserved.