Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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_Beginthread - Fatal编程技术网

Regex 在perl中使用正则表达式从文本块中提取子字符串或行

Regex 在perl中使用正则表达式从文本块中提取子字符串或行,regex,perl,beginthread,Regex,Perl,Beginthread,我有一个变量,里面有一些文本 $foo = " Garbage directory /test/this/is/a/directory /this/is/another/foo\nThisd is is\nDrop stuff testing\nRandom stuff emacs is great"; 如何使用regex获取/test/this/is/a/directory 我试过这个: my $foo = " Garbage directory /t

我有一个变量,里面有一些文本

$foo = "
    Garbage directory
    /test/this/is/a/directory
    /this/is/another/foo\nThisd is is\nDrop stuff testing\nRandom stuff emacs is great";
如何使用regex获取
/test/this/is/a/directory

我试过这个:

my $foo = "
    Garbage directory
    /test/this/is/a/directory
    /this/is/another/foo\nThisd is is\nDrop stuff testing\nRandom stuff emacs is great";
$foo =~ /^\/test.*$/;
print "\n$foo\n";

但这只会继续打印整个文本块。

您的正则表达式应该是:

/\/test.*\n/

原因是,您正在匹配整个文本,并且行尾没有限制。您需要表示希望与下一行匹配。不过,这个正则表达式在匹配中包含了换行符

对于正则表达式,有不同的实现方法,因此这取决于您试图实现的内容的上下文。您可以在末尾添加
m
修饰符。这样做的目的是将字符串视为多行,这样您就可以对每行而不是整个文本使用
^$
。另外,使用
m
多行修改器不会导致包含换行符的匹配

/\/test.*/m
就足够了

有关更多信息:

此外,
打印“$foo”
不会打印匹配项,因为
=~
运算符返回true或false值,并且不会将变量重新分配给匹配项。您需要更改模式匹配的正则表达式并打印第一个匹配项:

$foo =~ /(\/test.*)/m;
print $1;

把你的表情改成

$foo =~ m~^\s*/test.*$~m;



这将使用其他分隔符(
~
),这样您就不需要转义
/
,另外还需要空格(
\s*
),并打开
多行模式(
m
)。

OP似乎希望打印指定的行,而不是整个文本块。为此,我们需要修改Jan的答案以捕获和提取实际匹配

my $foo = "
    Garbage directory
    /test/this/is/a/directory
    /this/is/another/foo\nThisd is is\nDrop stuff testing\nRandom stuff emacs is great";
$foo =~ m~^(\s*/test.*)$~m;
$foo = $1;
print "\n$foo\n"
输出:

/test/this/is/a/directory

在您的案例中,什么定义了目录?也就是说,为什么
/this/is/other/foo
不是dir?否则,只需将表达式更改为
$foo=~~^\s*/test.*$~m为什么我们需要
\n
?我的评论纯粹基于正则表达式中的
\n
,因为它将捕获换行符以及匹配的一部分,这不是OP的要求。要求是匹配该行。从技术上讲,你可以说新线是一个微妙的,在大多数情况下,人们不想匹配,它没有明确说明在问题中。但这对否决票来说有点吹毛求疵。这对我来说非常有效,谢谢。我会接受这一点,因为这也解释了我的尝试失败的原因。@Borodin:真的需要两个
m
s吗?(这里不是
Perl
的家伙)。如果更改分隔符,则需要显式命名操作符
m~…~
。只有当你使用默认斜杠时,它才是可选的。谢谢你的解释,我真正需要的是$1。