简体   繁体   English

如何从Perl匹配运算符中将匹配提取到变量中?

[英]How can I extract the matches from the Perl match operator into variables?

If I have a match operator, how do I save the parts of the strings captured in the parentheses in variables instead of using $1 , $2 , and so on? 如果我有匹配运算符,如何将括号中捕获的字符串部分保存在变量中而不是使用$1$2等?

... = m/stuff (.*) stuff/;

What goes on the left? 左边的是什么?

The trick is to make m// work in list context by using a list assignment: 诀窍是通过使用列表赋值使m //在列表上下文中工作:

 ($interesting) = $string =~ m/(interesting)/g;

This can be neatly extended to grab more things, eg: 这可以整齐地扩展到抓住更多的东西,例如:

 ($interesting, $alsogood) = $string =~ m/(interesting) boring (alsogood)/g;

Use the bracketing construct (...) to create a capture buffer. 使用包围构造(...)创建捕获缓冲区。 Then use the special variables $1 , $2 , etc to access the captured string. 然后使用特殊变量$1$2等来访问捕获的字符串。

if ( m/(interesting)/ ) {
    my $captured = $1;
}

Usually you also want to do a test to make sure the input string matches your regular expression. 通常,您还需要进行测试以确保输入字符串与正则表达式匹配。 That way you can also handle error cases. 这样你也可以处理错误情况。

To extract something interesting you also need to have some way to anchor the bit you're interested in extracting. 要提取有趣的东西,你还需要有一些方法来锚定你有兴趣提取的位。

So, with your example, this will first make sure the input string matches our expression, and then extract the bit between the two 'boring' bits: 因此,在您的示例中,这将首先确保输入字符串与我们的表达式匹配,然后在两个“无聊”位之间提取位:

$input = "boring interesting boring";
if($input =~ m/boring (.*) boring/) {
    print "The interesting bit is $1\n";
}
else {
    print "Input not correctly formatted\n";
}

You can use named capture buffers: 您可以使用命名捕获缓冲区:

if (/ (?<key> .+? ) \s* : \s* (?<value> .+ ) /x) { 
    $hash{$+{key}} = $+{value};
}

@strings goes on the left and will contain result, then goes your input string $input_string . @strings在左边,包含结果,然后输入你的输入字符串$input_string Don't forget flag g for matching all substrings. 不要忘记标志g匹配所有子串。

my @strings=$input_string=~m/stuff (.*) stuff/g;

$& - The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). $& - 与上一次成功模式匹配匹配的字符串(不计算当前BLOCK包含的BLOCK或eval()中隐藏的任何匹配项)。

#! /usr/bin/perl

use strict;
use warnings;

my $interesting;
my $string = "boring interesting boring";
$interesting = $& if $string =~ /interesting/;

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

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