正则表达式捕获冒号分隔的键值对,具有多行值

2024-07-01

我目前正在 Ruby on Rails(在 Eclipse 中)中开发一个项目,我的任务是使用正则表达式将数据块拆分为相关部分。

我决定根据 3 个参数来分解数据:

  1. 该行必须以大写字母开头(正则表达式等效 -/^[A-Z]/)
  2. 它必须以 : (正则表达式等效项 -/$":"/)

我将不胜感激任何帮助......我在控制器中使用的代码是:

@f = File.open("report.rtf")  
@fread = @f.read  
@chunk = @fread.split(/\n/)

where @chunk是将通过分割创建的数组@fread是被分割的数据(通过换行符)。

任何帮助将不胜感激,非常感谢!

我无法发布确切的数据,但基本上是这样的(这与医学有关)

考试 1:CBW 8080

RESULT:

本报告是通过具体测量得出的。 请参阅报告原文。

比较:2012年1月30日、2012年3月8日、2012年4月9日

记录 1.1: 等等等等等等

理想的输出是一个数组,其中包含:

["Exam 1:", "CBW 8080", "RESULT", "This report is dictated with specific measurement. Please see the original report.", "COMPARISON:", "1/30/2012, 3/8/12, 4/9/12", "RECIST 1.1:", "BLAH BLAH BLAH"]

PS 我只是使用 \n 作为占位符,直到它正常工作


鉴于已澄清的问题,这是一个新的解决方案。

UPDATED

首先,将整个数据块(包括换行符和所有字符)“吸”成单个字符串。

str = IO.read("report.rtf")

然后使用这个正则表达式:

captures = str.scan(/(?<=^|[\r\n])([A-Z][^:]*):([^\r\n]*(?:[\r\n]+(?![A-Z].*:).*)*)/)

在这里查看一个实例:http://rubular.com/r/8w3X6WGq4l http://rubular.com/r/8w3X6WGq4l.

答案解释道:

    (?<=                Lookbehind assertion.
        ^                   Start at the beginning of the string,
        |                   or,
        [\r\n]              a new line.
    )
    (                   Capture group 1, the "key".
        [A-Z][^:]*          Capital letter followed as many non-colon
                            characters as possible.
    )
    :                   The colon character.

    (                   Capture group 2, the "value".
        [^\r\n]*            All characters (i.e. non-newline characters) on the
                            same line belongs to the "value," so take them all.

        (?:             Non-capture group.

            [\r\n]+         Having already taken everything up to a newline
                            character, take the newline character(s) now.

            (?!             Negative lookahead assertion.
                [^A-Z].*:       If this next line contains a capital letter,
                                followed by a string of anything then a colon,
                                then it is a new key/value pair, so we do not
                                want to match this case.
            )
            .*              Providing this isn't the case though, take the line!

        )*              And keep taking lines as long as we don't find a
                        key/value pair.
    )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式捕获冒号分隔的键值对,具有多行值 的相关文章

随机推荐