regular expression - match word only once in line

后端 未结 3 1012
一个人的身影
一个人的身影 2020-12-19 03:06

Case:

  1. ehello goodbye hellot hello goodbye
  2. ehello goodbye hello hello goodbye

I want to match line 1 (only has \'hello\' once!) DO NOT w

3条回答
  •  鱼传尺愫
    2020-12-19 03:28

    Since you're only worried about words (ie tokens separated by whitespace), you can just split on spaces and see how often "hello" appears. Since you didn't mention a language, here's an implementation in Perl:

    use strict;
    use warnings;
    
    my $a1="ehello goodbye hellot hello goodbye";
    my $a2="ehello goodbye hello hello goodbye";
    
    my @arr1=split(/\s+/,$a1);
    my @arr2=split(/\s+/,$a2);
    
    #grab the number of times that "hello" appears
    
    my $num_hello1=scalar(grep{$_ eq "hello"}@arr1);
    my $num_hello2=scalar(grep{$_ eq "hello"}@arr2);
    
    print "$num_hello1, $num_hello2\n";
    

    The output is

    1, 2
    

提交回复
热议问题