Check whether a string contains a substring
Solution 1
To find out if a string contains substring you can use the index
function:
if (index($str, $substr) != -1) {
print "$str contains $substr\n";
}
It will return the position of the first occurrence of $substr
in $str
, or -1 if the substring is not found.
Solution 2
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.
Solution 3
Case Insensitive Substring Example
This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:
if (index(lc($str), lc($substr)) != -1) {
print "$str contains $substr\n";
}
Belgin Fish
Updated on November 07, 2020Comments
-
Belgin Fish over 3 years
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 the given string variable. -
evgeny9 about 11 yearsThis way is especially preferrable, when you are searching using a variable - this way you won't have to double-escape characters (in this variable string), that are special for regular expressions (like
:
). -
G. Cito about 8 yearsI suppose
index()
is faster than regexps in the simple case? -
G. Cito about 8 yearsAn attempted perl answer to a question about removing substrings - I did not compare speed but
=~
,index()
,~~
andmatch::simple
all seemed a bitawk
-ward ... :-\ -
BlueChips23 over 7 yearsYou also have to make sure that the strings that you are comparing is not case sensitive. S1.DOMAIN.COM will not work for substring. But if you lc($givendomain), and then compare that with "s1.domain.com", then that will work. Also, substring is not necessarily the right approach - see my note above to eugene y's response
-
avrono over 7 years@David W. Somehow I can't get
domain.com
to matchsubdomain.domain.com
using the REGEX above, any ideas ? -
melpomene over 4 yearsNote that
fc
is recommended overlc
for case-insensitive comparisons. -
Sam B over 3 yearsSee this as well - troubleshooters.com/codecorn/littperl/perlreg.htm