在perl

时间:2016-06-21 22:16:54

标签: regex perl

我希望在匹配字符串“noon”

后提取花括号中的多行
  

file:exp.tcl

if { $time == "noon"} {

ready for lunch.

whats for food? {asian, korean}

going cafe or out?

}

我将文件存储在一个数组中并使用foreach循环读取它以执行其他正则表达式功能。我正在尝试extract_multiple但无法获得返回字符串。

2 个答案:

答案 0 :(得分:3)

Foreward

这种类型的模式匹配充满了边缘情况。但是如果您的输入字符串与您重新采样文本一样基本,那么您应该没问题。

描述

^.*?"noon".*?\{([\s\S]*?)^\}

Regular expression visualization

请注意,此表达式使用多行选项,使^与每行的开头匹配。

实施例

现场演示

https://regex101.com/r/vT9hM8/2

示例文字

if { $time == "noon"} {

ready for lunch.

whats for food? {asian, korean}

going cafe or out?

}

样本匹配

捕获组1将具有:

ready for lunch.

whats for food? {asian, korean}

going cafe or out?

解释

NODE                     EXPLANATION
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
----------------------------------------------------------------------
  "noon"                   '"noon"'
----------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
----------------------------------------------------------------------
  \{                       '{'
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    [\s\S]*?                 any character of: whitespace (\n, \r,
                             \t, \f, and " "), non-whitespace (all
                             but \n, \r, \t, \f, and " ") (0 or more
                             times (matching the least amount
                             possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  \}                       '}'
----------------------------------------------------------------------

答案 1 :(得分:0)

你的问题远非明确,这就是为什么我一直拒绝发布答案为止

除非检查一行是否包含字符串"noon",否则我不会使用正则表达式。还没有必要将您的文件读入数组

此单行打印所有行,以包含"noon"的行开头,以以右括号}

开头的行结束

如果你想要不同的东西,比如匹配嵌套大括号,那么你必须澄清你的问题

$ perl -ne '/"noon"/ .. /^\}/ and print' exp.tcl

输出

if { $time == "noon"} {

ready for lunch.

whats for food? {asian, korean}

going cafe or out?

}