简体   繁体   English

如何使用perl正则表达式匹配这样的东西?

[英]How do I match something like this using perl regex?

The file looks like 该文件看起来像

[N the computer end] [M whatever] [N you look] [N why not]

I only need the words in the bracket that start with [N so here I want to get the computer end you look why not they may or may not in the same line 我只需要以[N开头的括号中的单词,所以我想让计算机结束你看起来为什么不是它们可能也可能不在同一行

I tried something like this: 我试过这样的事情:

if($line =~/\[N(.+?)\]/)

but it only match the first one of each line. 但它只匹配每一行的第一行。

Use the g modifier on the regular expression to look for "g"lobal matches. 使用正则表达式上的g修饰符查找“g”lobal匹配。 Either like this: 要么像这样:

while ($line =~ /\[N(.+?)\]/g) {
    # $1 contains the text between "[N" and "]"
}

Or like this: 或者像这样:

my @matches = $line =~ /\[N(.+?)\]/g;
# @matches contains all of the matching items of text

You'll need to change it to a while loop to iterate over each group match. 您需要将其更改为while循环以迭代每个组匹配。 The Perl documentation illustrates this. Perl文档说明了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM