Check whether a string contains a substring

前端 未结 3 785
挽巷
挽巷 2020-11-29 19:08

How can I check whether a given string contains a certain substring, using Perl?

More specifically, I want to see whether s1.domain.com is present in th

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 19:38

    Another possibility is to use regular expressions which is what Perl is famous for:

    if ($mystring =~ /s1\.domain\.com/) {
       print qq("$mystring" contains "s1.domain.com"\n);
    }
    

    The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

    my $substring = "s1.domain.com";
        if ($mystring =~ /\Q$substring\E/) {
       print qq("$mystring" contains "$substring"\n);
    }
    

    Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

    Thus, this is an error:

    my $substring = "s1.domain.com";
    if (not index($mystring, $substr)) {
        print qq("$mystring" doesn't contains "$substring"\n";
    } 
    

    This will be wrong if s1.domain.com is at the beginning of your string. I've personally been burned on this more than once.

提交回复
热议问题