string Perl - 如果字符串包含文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7011524/
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:11:44  来源:igfitidea点击:

Perl - If string contains text?

stringperlstring-matching

提问by Hellos

I want to use curl to view the source of a page and if that source contains a word that matches the string then it will execute a print. How would I do a if $string contains?

我想使用 curl 查看页面的来源,如果该来源包含与字符串匹配的单词,则它将执行打印。我该怎么做if $string contains

In VB it would be like.

在VB中它会像。

dim string1 as string = "1"
If string1.contains("1") Then
Code here...
End If

Something similar to that but in Perl.

类似的东西,但在 Perl 中。

回答by Eugene Yarmash

If you just need to search for one string within another, use the indexfunction (or rindexif you want to start scanning from the end of the string):

如果您只需要在另一个字符串中搜索一个字符串,请使用该index函数(或者rindex如果您想从字符串的末尾开始扫描):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a patternmatch, use the match operator m//:

要在字符串中搜索模式匹配,请使用匹配运算符m//

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

回答by Sean Bright

if ($string =~ m/something/) {
   # Do work
}

Where somethingis a regular expression.

哪里something是正则表达式。