【问题标题】:Ruby and Regex ImprecisionRuby 和正则表达式不精确
【发布时间】:2013-05-31 15:29:05
【问题描述】:

我正在尝试使用 Ruby 和 Regex 将一个长字符串分成由整个字符串中出现的时间戳分隔的块。

“10:59 am Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at tincidunt >ante。3:30 am Aenean interdum, quam sed tempor imperdiet, neque turpis aliquet est, at >luctus justo arcu et arcu. Sed sat amet eros a sem hendrerit vestibulum faucibus sat amet >nunc。Nam venenatis pharetra leo vel facilisis。晚上 9:20 Aenean tincidunt ligula lacinia。"

这是我为提取每个块而运行的循环。

while text.length > 1
  begin_entry = text.index(/\d{1,2}[:]\d{2}\s(a|p)[.][m][.]/)
  end_entry = text.index(/\d{1,2}[:]\d{2}\s(a|p)[.][m][.]/, begin_entry + 1)
  blot = text.slice!(begin_entry, end_entry)
end

当我运行它时,开始条目的第一个时间戳被捕获 find。然而,结局永远不会对。

而不是“上午 10:59 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at tincidunt ante”。我得到“”上午 10:59 Lorem ipsum dolor sit amet,consectetur adipiscing elit。 Phasellus 在 tincidunt ante。凌晨 3 点 30 分。”

随着循环遍历字符串,事情变得更加糟糕。条目的开头总是正确的,时间戳包含在子字符串的开头。然而,结局永远不会。

【问题讨论】:

    标签: ruby regex rubular


    【解决方案1】:
    text.split(/(\d{1,2}:\d{1,2}\s[ap]\.m\.)/).drop(1).each_slice(2).map(&:join)
    

    【讨论】:

    • 谢谢!这样可行。但我想知道为什么尝试没有奏效?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多