ruby - 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?
解决方案
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('/') }
推荐阅读
- javascript - Javascript中的三重引号
- python - 在tex中写方程时使用变量。循环变量以编写不同的方程
- angular - 如何调试 RxJS / Angular?发出新值时视图不更新
- multithreading - 如何通过负载均衡进行对称矩阵的计算?
- javascript - ReactJs hook reducer 通过基于用户字符串输入的数组进行过滤
- python - 从多个列表创建数据框
- ios - SwiftUI 中具有双重动作(点击和长按)的按钮
- jekyll - Windows 10 安装 jekyll 错误,我该怎么办?
- python-3.x - 为什么我无法通过 python zipfile 解压缩压缩文件?
- nlp - 将 gensim wordVectors init_sim 属性设置为 True 错误 - ValueError: output array is read-only