1

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

$foo = "
    Garbage directory
    /test/this/is/a/directory
    /this/is/another/foo\nThisd is is\nDrop stuff testing\nRandom stuff emacs is great";

我如何使用正则表达式来获取行/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";

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

4

3 回答 3

1

将您的表达式更改为

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

在 regex101.com 上查看演示


这使用了其他定界符 ( ~),因此您不需要转义/、另外的空格 ( \s*) 并打开multiline模式 ( m)。

于 2018-05-23T20:28:06.600 回答
1

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
于 2018-05-23T20:56:02.307 回答
-1

你的正则表达式应该是:

/\/test.*\n/

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

使用正则表达式有不同的方法可以做到这一点,因此这取决于您要完成的内容的上下文。您可以m在最后添加修饰符。这将做的是将字符串视为多行,以便您可以使用^$每一行而不是整个文本。同样使用m多行修饰符不会导致包含换行符的匹配。

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

欲了解更多信息:https ://perldoc.perl.org/perlre.html

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

$foo =~ /(\/test.*)/m;
print $1;
于 2018-05-23T20:25:50.810 回答