Perl:如何提取方括号之间的字符串 [英] Perl: How to extract a string between brackets

查看:650
本文介绍了Perl:如何提取方括号之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个moinmoin文本格式的文件:

I have a file in moinmoin text format:

* [[  Virtualbox Guest Additions]] (2011/10/17 15:19)
* [[  Abiword Wordprocessor]] (2010/10/27 20:17)
* [[  Sylpheed E-Mail]] (2010/03/30 21:49)
* [[   Kupfer]] (2010/05/16 20:18)

"[["和]]"之间的所有单词均为条目的简短描述.我需要提取整个条目,而不是每个单词.

All the words between the '[[' and ']]' are the short description of the entry. I need to extract the whole entry, but not each individual word.

我在这里找到了类似问题的答案: https://stackoverflow.com/a/2700749/819596 但无法理解答案:"my @array = $str =~ /( \{ (?: [^{}]* | (?0) )* \} )/xg;"

I found an answer for a similar question here: https://stackoverflow.com/a/2700749/819596 but can't understand the answer: "my @array = $str =~ /( \{ (?: [^{}]* | (?0) )* \} )/xg;"

任何有效的方法都会被接受,但是解释会大有帮助,例如:(?0)/xg的作用.

Anything that works will be accepted but explanations would help greatly, ie: what (?0) or /xg does.

推荐答案

如果文本永远不包含],则可以按照以前的建议简单地使用以下内容:

If the text will never contain ], you can simply use the following as previously recommended:

/\[\[ ( [^\]]* ) \]\]/x

以下内容允许在包含的文本中使用],但我建议不要将其合并到较大的模式中:

The following allows ] in the contained text, but I recommend against incorporating it into a larger pattern:

/\[\[ ( .*? ) \]\]/x

以下内容允许在包含的文本中使用],这是最可靠的解决方案:

The following allows ] in the contained text, and is the most robust solution:

/\[\[ ( (?:(?!\]\]).)* ) \]\]/x

例如,

if (my ($match) = $line =~ /\[\[ ( (?:(?!\]\]).)* ) \]\]/x) {
   print "$match\n";
}

my @matches = $file =~ /\[\[ ( (?:(?!\]\]).)* ) \]\]/xg;


  • /x:忽略模式中的空格.允许添加空格以使模式可读,而无需更改模式的含义.在 perlre 中记录.
  • /g:查找所有匹配项.在 perlop 中记录.
  • (?0)用于使模式递归,因为链接的节点必须处理任意的curlies嵌套. * /g:查找所有匹配项.在 perlre 中记录.

    • /x: Ignore whitespace in pattern. Allows spaces to be added to make the pattern readable without changing the meaning of the pattern. Documented in perlre.
    • /g: Find all matches. Documented in perlop.
    • (?0) was used to make the pattern recursive since the linked node had to deal with arbitrary nesting of curlies. * /g: Find all matches. Documented in perlre.
    • 这篇关于Perl:如何提取方括号之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆