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

Joh*_*ugh 4 ruby regex eclipse ruby-on-rails

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

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

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

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

@f = File.open("report.rtf")  
@fread = @f.read  
@chunk = @fread.split(/\n/)
Run Code Online (Sandbox Code Playgroud)

其中@chunk是将由拆分创建的数组,@fread是要拆分的数据(按新行)。

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

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

考试 1:CBW 8080

结果:

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

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

RECIST 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"]
Run Code Online (Sandbox Code Playgroud)

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

And*_*ong 5

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

更新

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

str = IO.read("report.rtf")
Run Code Online (Sandbox Code Playgroud)

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

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

请参阅此处的实例: 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.
    )
Run Code Online (Sandbox Code Playgroud)