gpt4 book ai didi

ruby - 如何编写能够匹配一行或两行文本的正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:14 24 4
gpt4 key购买 nike

我试图匹配一些可以是一行或两行的文本。我希望能够有效地处理这两种情况。文本字符串将采用一致的格式并包含多个选项卡。我正在尝试用 ruby 进行比赛。正文如下:

单行:

#3  Hello Stormy    Scratched - Reason Unavailable                           11:10 AM ET 

两行:

#3  Hello Stormy    Scratched - Reason Unavailable                            11:10 AM ET   
Scratch Reason - Reason Unavailable changed to Trainer 2:19 PM ET

我不得不在此处使用空格来格式化字符串,但实际文本使用制表符分隔各个部分:编号和名称、Scratched、原因和时间。

示例输出:

一行:#3 Hello Stormy Scratched - Reason Unavailable 11:10AM ET

两行#3 Hello Stormy Scratched - Reason Unavailable 更改为 Trainer 2:19PM

注意:理想情况下,两行输出将包括第一行中的数字和名称。

我能够构建一个匹配各个部分的表达式,但是制表符、第二行以及要求在两行输出中包含数字和马名的要求给我带来了麻烦。

最佳答案

你不需要花哨的正则表达式来做你想做的事,你只需要知道如何去做。

Ruby 的 Enumerable 有一个名为 slice_before 的方法它采用正则表达式,用于确定数组中的哪些元素组合在一起。 Array 继承自 Enumerable。例如:

text = '#3  Hello Stormy    Scratched   -   Reason Unavailable          11:10 AM ET
#3 Hello Stormy Scratched - Reason Unavailable 11:10 AM ET
Scratch Reason - Reason Unavailable changed to Trainer 2:19 PM ET
'

data = text.split("\n").slice_before(/\A\S/).to_a

require 'pp'
pp data

输出:

[["#3\tHello Stormy\tScratched\t-\tReason Unavailable\t\t\t11:10 AM ET"],
["#3\tHello Stormy\tScratched\t-\tReason Unavailable\t\t\t11:10 AM ET",
"\t\t\tScratch\tReason\t-\tReason Unavailable changed to Trainer\t2:19 PM ET"]]

换句话说,通过拆分 "\n" 上的文本创建的数组按不以空格开头的行分组,这是模式 /\A\S/。所有单行都在单独的子数组中。上一行的延续行与该行分组。

如果您正在从磁盘读取文件,您可以使用 IO.readlines 将文件作为数组读取,避免拆分文件的需要。

如果需要,您可以进一步处理该数组以重建行和续行,使用类似的东西:

data = text.split("\n").slice_before(/\A\S/).map{ |i| i.join("\n") }

data 变成:

["#3\tHello Stormy\tScratched\t-\tReason Unavailable\t\t\t11:10 AM ET",
"#3\tHello Stormy\tScratched\t-\tReason Unavailable\t\t\t11:10 AM ET\n\t\t\tScratch\tReason\t-\tReason Unavailable changed to Trainer\t2:19 PM ET"]

如果您需要将每一行拆分为其组成字段,请使用 split("\t")。如何跨子数组执行此操作留给您作为练习,但我会涉及 map


编辑:

...I like your solution, but I'm getting undefined method for slice_before.

试试这个:

require 'pp'
require 'rubygems'

class Array

unless Array.respond_to?(:slice_before)
def slice_before(pat)
result = []
temp_result = []
self.each do |i|

if (temp_result.empty?)
temp_result << i
next
end

if i[pat]
result << temp_result
temp_result = []
end

temp_result << i
end
result << temp_result

end
end

end

这样调用:

ary = [
'#3 Hello Stormy Scratched - Reason Unavailable 11:10 AM ET',
'#3 Hello Stormy Scratched - Reason Unavailable 11:10 AM ET',
' Scratch Reason - Reason Unavailable changed to Trainer 2:19 PM ET',
]

pp ary.slice_before(/\A\S/)

看起来像:

[
["#3 Hello Stormy Scratched - Reason Unavailable 11:10 AM ET"],
["#3 Hello Stormy Scratched - Reason Unavailable 11:10 AM ET",
" Scratch Reason - Reason Unavailable changed to Trainer 2:19 PM ET"]
]

关于ruby - 如何编写能够匹配一行或两行文本的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com