string 检查字符串是否包含子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7283274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:12:42  来源:igfitidea点击:

Check whether a string contains a substring

stringperlstring-matching

提问by Belgin Fish

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

如何使用 Perl 检查给定字符串是否包含某个子字符串?

More specifically, I want to see whether s1.domain.comis present in the given string variable.

更具体地说,我想查看s1.domain.com给定的字符串变量中是否存在。

回答by Eugene Yarmash

To find out if a string contains substring you can use the indexfunction:

要确定字符串是否包含子字符串,您可以使用该index函数:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substrin $str, or -1 if the substring is not found.

它将返回第一次出现$substrin的位置,$str如果未找到子字符串,则返回-1。

回答by David W.

Another possibility is to use regular expressionswhich is what Perl is famous for:

另一种可能性是使用正则表达式,这正是 Perl 的著名之处:

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 \Qand \Eoperators.

需要反斜杠,因为 a.可以匹配任何字符。您可以使用\Qand\E运算符来解决这个问题。

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

Or, you can do as eugene ystated and use the indexfunction. Just a word of warning: Index returns a -1when it can't find a match instead of an undefor 0.

或者,您可以按照eugene y 的说明进行操作并使用index函数。只是一个警告:索引-1在找不到匹配项时返回 a而不是undefor 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.comis at the beginning of your string. I've personally been burned on this more than once.

如果s1.domain.com在字符串的开头,这将是错误的。我个人不止一次被这件事激怒。

回答by James Oravec

Case Insensitive Substring Example

不区分大小写的子字符串示例

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

这是 Eugene 答案的扩展,它在检查子字符串之前将字符串转换为小写:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";
}