首页 > 解决方案 > regex match and split in ruby

问题描述

I have an big string of this format:

FA dir_name1 file_name1
FA dir_name1 file_name2
FA dir_name2 file_name1
FA dir_name2 file_name2
....

I was thinking if we can write an regex expression while doing split which returns me an array consisting of this:

["dir_name1/file_name1", "dir_name1/file_name2", "dir_name2/file_name1", "dir_name2/file_name2"]

I have tried splitting the big string first and then do regex. It works but can't we do it using easier way?

Any other way to do this?

标签: ruby

解决方案


As you wish to get an array out of string, some split is required.

input.scan(/(?<=^FA ).*$/).
      map { |e| e.split.join('/') }
#⇒ [
#   [0] "dir_name1/file_name1",
#   [1] "dir_name1/file_name2",
#   [2] "dir_name2/file_name1",
#   [3] "dir_name2/file_name2"
#  ]

It scans the input using positive lookbehind to get the desired result out of the box, splits it by space and joins with a slash.


Another way round would be to just split several times:

input.
  split($/).
  map { |line| line.split[1..-1].join('/') }

推荐阅读