Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 在Perl中提取子字符串?_Regex_Perl - Fatal编程技术网

Regex 在Perl中提取子字符串?

Regex 在Perl中提取子字符串?,regex,perl,Regex,Perl,变量中有一个字符串: $mystr = "some text %PARTS/dir1/dir2/myfile.abc some more text"; 现在%部分确实存在于字符串中,它不是变量或散列。 我想从中提取子字符串%PARTS/dir1/dir2/myfile.abc。我创建了以下reg表达式。我只是Perl的初学者。所以,如果我做错了什么,请告诉我 my $local_file = substr ($mystr, index($mystr, '%PARTS'), index($mys

变量中有一个字符串:

$mystr = "some text %PARTS/dir1/dir2/myfile.abc some more text";
现在%部分确实存在于字符串中,它不是变量或散列。 我想从中提取子字符串
%PARTS/dir1/dir2/myfile.abc
。我创建了以下reg表达式。我只是Perl的初学者。所以,如果我做错了什么,请告诉我

my $local_file = substr ($mystr, index($mystr, '%PARTS'), index($mystr, /.*%PARTS ?/));
我甚至试过:

my $local_file = substr ($mystr, index($mystr, '%PARTS'), index($mystr, /.*%PARTS' '?/));
但如果我打印
$local\u文件
,两者都不会给出任何信息。 这里可能出了什么问题? 多谢各位

更新:参考了以下网站使用此方法:

  • 参见示例1c

  • index
    函数返回字符串中出现的子字符串的第一个索引,否则
    -1
    。它与正则表达式无关

    正则表达式通过绑定运算符
    =~
    应用于字符串

    要提取正则表达式的匹配区域,请将模式包含在parens(捕获组)中。匹配的子字符串将在
    $1
    中提供:

    my $str = "some text %PARTS/dir1/dir2/myfile.abc some more text";
    if ($str =~ /(%PARTS\S+)/) {
      my $local_file = $1;
      ...; # do something
    } else {
      die "the match failed"; # do something else
    }
    
    \S
    字符类将匹配每个非空格字符

    要了解正则表达式,可以查看。

    该函数与regexp无关。它的参数只是字符串,而不是正则表达式。所以你的用法是错误的

    是Perl的一个强大功能,也是执行此任务最合适的工具:

    my ($local_file) = $mystr =~ /(%PARTS[^ ]+)/;
    

    有关
    =~
    运算符的更多信息,请参阅。

    @stema:如果不使用捕获组,则无法直接分配匹配的零件。如果使用
    $&
    ,则可以避免使用组;如果使用组或列表上下文加上
    /g
    ,则可以避免使用
    $1
    。错误示例。您没有检查正则表达式是否失败,这可能会导致其他正则表达式执行中留下$1集。最简单的方法如dolmen的回答所示。谢谢你的回答@dolmen