匹配单词的第一个字母

Matching first letter of word

我想将一个字符串中某个单词的第一个字母与另一个具有相似字母的单词进行匹配。在此示例中,字母 H:

25HB matches to HC

我正在使用如下所示的匹配运算符:

my ($match) = ( $value =~ m/^d(\w)/ );

不匹配数字,而是匹配单词的第一个字符。我该如何纠正?

正则表达式与您认为的不一样:

m/^d(\w)/ 

匹配 'start of line' - 字母 d 然后是单个 word character

您可能需要:

m/^\d+(\w)/ 

然后将从行首匹配一个或多个 数字 ,然后获取第一个 word character

例如:

my $string = '25HC'; 

my ( $match ) =( $string =~ m/^\d+(\w)/ );
print $match,"\n";

打印 H

你可以试试^.*?([A-Za-z])

以下代码returns:

ITEM: 22hb
MATCH: h

ITEM: 33HB
MATCH: H

ITEM: 3333
MATCH:

ITEM: 43 H
MATCH: H

ITEM: HB33
MATCH: H

脚本。

#!/usr/bin/perl

my @array = ('22hb','33HB','3333','43 H','HB33');
for my $item (@array) {
    my $match =  if $item =~ /^.*?([A-Za-z])/;
    print "ITEM: $item \nMATCH: $match\n\n";
}

我相信这就是您要找的:

(如果您能提供更清楚的示例来说明您正在寻找的内容,我们可能会更好地帮助您)

以下代码采用两个字符串并查找两个字符串中共有的第一个非数字字符:

my $string1 = '25HB';
my $string2 = 'HC';

#strip all digits
$string1 =~ s/\d//g;
foreach my $alpha (split //, $string1) {
    # for each non-digit check if we find a match
    if ($string2 =~ /$alpha/) {
        print "First matching non-numeric character: $alpha\n";
        exit;
    }
}

你不清楚自己想要什么。如果要将字符串中的第一个字母与字符串中后面的相同字母匹配:

m{
  (              # start a capture
    [[:alpha:]]  # match a single letter
  )              # end of capture
  .*?            # skip minimum number of any character
               # match the captured letter
}msx;            # /m means multilines, /s means . matches newlines, /x means ignore whitespace in pattern

有关详细信息,请参阅 perldoc perlre

附录:

如果按单词,你指的是任何字母数字序列,这可能更接近你想要的:

m{
  \b             # match a word boundary (start or end of a word)
  \d*            # greedy match any digits
  (              # start a capture
    [[:alpha:]]  # match a single letter
  )              # end of capture
  .*?            # skip minimum number of any character
  \b             # match a word boundary (start or end of a word)
  \d*            # greedy match any digits
               # match the captured letter
}msx;            # /m means multilines, /s means . matches newlines, /x means ignore whitespace in pattern