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

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

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

  1. 该行必须以大写字母开头(RegEx等价 – /^[AZ]/
  2. 它必须以:( RegEx等价物 – /$":"/ )结束

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

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

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

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

我无法发布确切的数据,但它基本上是由此(这在医学上相关)

考试1:CBW 8080

结果:

该报告由具体测量决定。 请参阅原始报告。

比较:2012年1月30日,3/8/12,4/9/12

RECIST 1.1:BLAH BLAH BLAH

理想的输出是一个数组,表示:

 ["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作为占位符,直到我开始工作

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

更新

首先将整个数据块(包括换行符和全部)“Slurp”为单个字符串。

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

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

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

请参阅此处的实例: 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". [AZ][^:]* Capital letter followed as many non-colon characters as possible. ) : The colon character. ( Capture group 2, the "value". [^\r\n]* All characters (ie 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. [^AZ].*: 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. ) 

我不完全确定你在寻找什么。 如果你想要所有出现的大写字母后跟一些文本和分号,那么你可以这样做:

 str.scan(/[AZ].*?:/) 

这应该做到这一点。

 /^[AZ].*:$/ 

正则表达式可以是:/( /(^[AZ].*\:)/m :)/ /(^[AZ].*\:)/m并通过添加以下内容进行提取:

 @chunk = @fread.scan(/(^[AZ].*\:)/m) 

提供@fread是一个字符串。 您可以使用http://rubular.com/在ruby中测试正则表达式。

又一个解决方案:

 input_str.split("\r\n").each |s| do var_name = s.split(": ")[0] var_value = s.split(": ")[1] # do whatever you like done