使用 perl 在字符串中搜索特定的子字符串模式

search a specific sub string pattern in a string using perl

我是 perl 的新手,我了解了这个 Check whether a string contains a substring 如何检查字符串中是否存在子字符串,现在我的情况有点不同

我有一个像

这样的字符串

/home/me/Desktop/MyWork/systemfile/directory/systemfile64.elf ,

最后这可能是 systemfile32.elfsystemfile16.elf,所以在我的 perl 脚本中我需要检查这个字符串是否包含格式为 systemfile*.elf 的子字符串。 我怎样才能在 perl 中实现这个?

我打算这样做

if(index($mainstring, _serach_for_pattern_systemfile*.elf_ ) ~= -1) {
    say" Found the string";
}

您可以使用模式匹配

if ($string =~ /systemfile\d\d\.elf$/){
   # DoSomething
}

\d代表一个数字(0-9)

$代表字符串结束

if( $mainstring =~ m'/systemfile(16|32)\.elf$' ) {
   say" Found the string";
}

完成任务。


供您参考:

$string =~ m' ... '

相同
$string =~ / ... /

根据给定的正则表达式检查字符串。这是 Perl 语言最有用的特性之一。

更多信息请访问 http://perldoc.perl.org/perlre.html

(我确实使用了 m'' 语法来提高可读性,因为正则表达式中存在另一个 '/' 字符。我也可以写 /\/systemfile\d+\.elf$/

use strict;
use warnings;

my $string = 'systemfile16.elf';
if ($string =~ /^systemfile.*\.elf$/) {
print "Found string $string";
  } else {
print "String not found";

如果您有设置的目录,将匹配 systemfile'anythinghere'.elf。

如果要搜索整个字符串,包括目录,则:

my $string = 'c:\windows\system\systemfile16.elf';
if ($string =~ /systemfile.*\.elf$/) {
print "Found string $string";
  } else {
print "String not found";

如果你只想匹配2个系统文件然后2个数字字符.elf然后使用其他答案上面提到的其他方法。但是如果你想要 systemanything.elf 然后使用其中之一。

if ($string =~ /systemfile.*\.elf/) {
    # Do something with the string.
}

那应该只匹配您查找的字符串(假设每次给定的字符串都存储在 $string 中)。在大括号内你应该写下你的逻辑。

.代表"any character",*代表"as many times you see the last character"。所以,.* 表示 "any character as many times you see it"。如果您知道字符串将以这种模式结束,那么在模式末尾添加 $ 以标记字符串应以这种方式结束会更安全:

$string =~ /systemfile.*\.elf$/

只是不要忘记 chomp $string 以避免任何可能会干扰您所需输出的换行符。