简体   繁体   English

Perl如何为正则表达式匹配结果分配变量

[英]Perl how do you assign a varanble to a regex match result

How do you create a $scalar from the result of a regex match? 如何根据正则表达式匹配的结果创建$ scalar? Is there any way that once the script has matched the regex that it can be assigned to a variable so it can be used later on, outside of the block. 有什么办法可以使脚本与正则表达式匹配后,就可以将其分配给变量,以便稍后在块外使用。 IE. IE浏览器。 If $regex_result = blah blah then do something. 如果$regex_result = blah blah那就做点什么。 I understand that I should make the regex as non-greedy as possible. 我知道我应该使正则表达式尽可能不贪心。

#!/usr/bin/perl
use strict;
use warnings;
# use diagnostics;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Outlook';
my @Qmail;

my $regex = "^\\s\*owner \#";
my $sentence = $regex =~ "/^\\s\*owner \#/";

my $outlook = Win32::OLE->new('Outlook.Application')
    or warn "Failed Opening Outlook.";
my $namespace = $outlook->GetNamespace("MAPI");
my $folder    = $namespace->Folders("test")->Folders("Inbox");
my $items     = $folder->Items;

foreach my $msg ( $items->in ) {
    if ( $msg->{Subject} =~ m/^(.*test alert) / ) {
        my $name = $1;
        print "  processing Email for $name \n";
        push @Qmail, $msg->{Body};
    }
}

for(@Qmail) {
  next unless /$regex|^\s*description/i;
  print; # prints what i want ie lines that start with owner and description
}

print $sentence; # prints ^\\s\*offense \ # not lines that start with owner.

One way is to verify a match occurred. 一种方法是验证是否发生匹配。

use strict;
use warnings;

my $str = "hello what world";

my $match  = 'no match found';
my $what  = 'no what found';
if ( $str =~ /hello (what) world/ )
{
   $match = $&;
   $what = $1;
}

print '$match = ', $match, "\n";
print '$what = ', $what, "\n";

The match of a regex is stored in special variables (as well as some more readable variables if you specify the regex to do so and use the /p flag). 正则表达式的匹配项存储在特殊变量中(如果您指定正则表达式并使用/p标志,还会存储一些更易读的变量)。

For the whole last match you're looking at the $MATCH (or $& for short) variable. 对于整个上一场比赛,您正在查看$MATCH (或简称$& )变量。 This is covered in the manual page perlvar . 手册页perlvar对此进行了介绍。

So say you wanted to store your last for loop's matches in an array called @matches , you could write the loop (and for some reason I think you meant it to be a foreach loop) as: 因此,假设您要将最后一个for循环的匹配项存储在名为@matches的数组中,则可以将循环编写为(由于某种原因,我认为您希望它是一个foreach循环),如下所示:

my @matches = ();
foreach (@Qmail) {
    next unless /$regex|^\s*description/i;
    push @matches_in_qmail $MATCH
    print;
}

I think you have a problem in your code. 我认为您的代码有问题。 I'm not sure of the original intention but looking at these lines: 我不确定最初的意图,但请看以下几行:

my $regex = "^\\s\*owner \#";
my $sentence = $regex =~ "/^\s*owner #/";

I'll step through that as: 我将通过以下步骤:

  • Assign $regex to the string ^\\s*owner # . $regex分配给字符串^\\s*owner #
  • Assign $sentence to value of running a match within $regex with the regular expression /^s*owner $/ (which won't match, if it did $sentence will be 1 but since it didn't it's false). $sentence分配给在$regex使用正则表达式/^s*owner $/匹配的值(如果匹配,则$sentence1但不会匹配,这是不正确的,否则将不匹配)。

I think. 我认为。 I'm actually not exactly certain what that line will do or was meant to do. 实际上,我不确定该行将要执行或应执行的操作。

I'm not quite sure what part of the match you want: the captures, or something else. 我不太确定您想要比赛的哪一部分:捕获或其他内容。 I've written Regexp::Result which you can use to grab all the captures etc. on a successful match, and Regexp::Flow to grab multiple results (including success statuses). 我编写了Regexp :: Result ,您可以使用它来捕获成功匹配中的所有捕获内容,以及Regexp :: Flow来捕获多个结果(包括成功状态)。 If you just want numbered captures, you can also use Data::Munge 如果只需要编号捕获,也可以使用Data :: Munge

You can do the following: 您可以执行以下操作:

my $str ="hello world";  
my ($hello, $world) = $str =~ /(hello)|(what)/; 

say "[$_]" for($hello,$world);

As you see $hello contains "hello". 如您所见,$ hello包含“ hello”。

Use Below Perl variables to meet your requirements - 使用Perl以下变量来满足您的要求-

$` = The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already. $`=最后一个模式匹配所匹配的字符串,不包括已经退出的嵌套块中匹配的模式。

$& = Contains the string matched by the last pattern match $&=包含最后一个模式匹配所匹配的字符串

$' = The string following whatever was matched by the last pattern match, not counting patterns matched in nested blockes that have been exited already. $'=上一个模式匹配所匹配的字符串,不包括已退出的嵌套块中匹配的模式。 For example: 例如:

$_ = 'abcdefghi';
/def/; 
print "$`:$&:$'\n";    # prints abc:def:ghi

If you have older perl on your system like me, perl 5.18 or earlier, and you use $ $& $' like codequestor's answer above, it will slow down your program. 如果您的系统中有像我这样的perl,perl 5.18或更早版本的perl,并且像上述codequestor的答案一样使用$ $& $' ,它将减慢您的程序速度。

Instead, you can use your regex pattern with the modifier /p , and then check these 3 variables: ${^PREMATCH} , ${^MATCH} , and ${^POSTMATCH} for your matching results. 相反,您可以将正则表达式模式与修饰符/p ,然后检查以下三个变量: ${^PREMATCH}${^MATCH}${^POSTMATCH}以获取匹配结果。

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

相关问题 Perl正则表达式:你如何匹配perl中的多个单词? - Perl regex: How do you match multiple words in perl? Perl,将正则表达式匹配赋予标量 - Perl, Assign regex match to scalar 您如何将[]与正则表达式匹配? - How do you match [ ] with regex? 如何在Perl中进行简单的正则表达式匹配和分配操作? 我是否在正确的轨道上:if($ file =〜m /(music \\ /(。*)。*)$ /) - How do I do a simple regex match and assign operation in perl? Am I on right track with: if( $file =~ m/(music\/(.*).*)$/ ) Perl如何进行可选的正则表达式匹配 - Perl How to do optional regex match 如何在一行中将正则表达式匹配的结果分配给新变量? - How do I assign the result of a regex match to a new variable, in a single line? 如何在数组中找到与文本文件中的关键字匹配的内容以及在perl中执行正则表达式时的内容 - How do you find something in an array that would match keywords from a text file and while doing a regex in perl Perl将regex匹配赋值给具有默认值的变量 - Perl assign regex match to variable with default value Perl将正则表达式匹配组分配给变量 - Perl assign regex match groups to variables 在Python正则表达式matchobj中,如何进行子字符串匹配,并将匹配项分配给变量? - in a Python regex matchobj, how to do a substring match, and assign the match to a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM