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
Perl - If string contains text?
提问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 index
function (or rindex
if 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//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
回答by Sean Bright
if ($string =~ m/something/) {
# Do work
}
Where something
is a regular expression.
哪里something
是正则表达式。