2015-05-20 174 views
-1

我想匹配一个字符串中的一个单词的第一个字母与另一个相似的字母。在这个例子中,字母H:匹配单词的第一个字母

25HB matches to HC 

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

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

不匹配的数字,但第一个匹配的单词字符。我怎么能纠正这个?

+0

'\ w'包含字母,数字和下划线。只有字母的选项可能是'[[:alpha:]''''\ p {PosixAlpha}]或'[\ p {XPosixAlpha}]'。 – tjd

+2

您的模式表示您希望字符串的起始字符'd'和来自'\ w'字符组的一个字符。我建议你看看这个:https:// regex101。com/r/bQ8bM7/1 – simbabque

+0

另外我不明白目标是什么。你的例子中的“HC”在哪里?你能显示样本输入和样本输出,还是试图用不同的词来解释? – simbabque

回答

1

该正则表达式不会做你认为它的作用:

m/^d(\w)/ 

匹配“行首” - 信d话单word character

你可能想:

m/^\d+(\w)/ 

然后将匹配一个或多个数字行的开始,并抓住后第一word character

例如为:

my $string = '25HC'; 

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

打印H

1

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

下面的代码返回:

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 = $1 if $item =~ /^.*?([A-Za-z])/; 
    print "ITEM: $item \nMATCH: $match\n\n"; 
} 
0

我相信这是你在找什么:

(如果你可以提供你正在寻找更明显的例子,因为我们也许能够帮助你更好)

以下代码需要两个字符串,并在两个字符串中找到第一个非数字字符:

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; 
    } 
} 
1

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

m{ 
    (    # start a capture 
    [[:alpha:]] # match a single letter 
)    # end of capture 
    .*?   # skip minimum number of any character 
    \1    # 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 
    \1    # match the captured letter 
}msx;   # /m means multilines, /s means . matches newlines, /x means ignore whitespace in pattern 
+0

你说得对,我的例子并不清楚。我想检查这个词的第一个字母是否匹配。这很难说清楚,但在12HB和56HA中,H将成为每首歌的首字母,也是一场比赛。感谢您的输入! – EA00

相关问题