检查字符串是否包含字符
我试图执行一个简单的检查来查看字符串是否包含“%”,但是每当我执行代码时,无论字符串中是什么,它都会将 if 语句评估为 false。我的代码如下所示:
if ($end_time =~ m{%%}) {
($percentage) = $end_time =~ m/=([^%%]*)%%/g;
$percentage = sprintf("%s%%", $percentage);
$end_time = "";
}
elsif ($duration =~ m/(overdue)/) {
$percentage = "$end_time $duration";
$end_time = "";
}
else {
$percentage = "100%";
}
以及 $end_time 的预期值,替换您喜欢的任何数值。
"5%" or "==30%" or "+3m:26s overdue" or "13:48:40"
因此,如果 $end_time 包含“逾期”或“%”,百分比将为 100%,并且 $end_time 将是检查之前的内容。我确实理解为什么我得到了我得到的结果,而不是我的 if 语句总是被评估为错误的原因。
I am trying to perform a simple check to see if a string contains a "%" but whenever I execute my code it will evaluate the if statement as false no matter what is in the string. My code looks like this:
if ($end_time =~ m{%%}) {
($percentage) = $end_time =~ m/=([^%%]*)%%/g;
$percentage = sprintf("%s%%", $percentage);
$end_time = "";
}
elsif ($duration =~ m/(overdue)/) {
$percentage = "$end_time $duration";
$end_time = "";
}
else {
$percentage = "100%";
}
and the expected values of $end_time, substitute whatever numeric values you like.
"5%" or "==30%" or "+3m:26s overdue" or "13:48:40"
So if $end_time contains "overdue" or a "%" percentage will be 100% and $end_time will be whatever was in there before the check. And I do understand why I'm getting the results I'm getting, just not the reason my if statements are always evaluating as false.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串文字和正则表达式文字使用
\
转义,而不是通过加倍转义,并且%
都不需要转义。sprintf
采用带有双倍%
的字符串来指示%
,但这与构建字符串和正则表达式模式无关。String literals and regex literals escape with
\
, not by doubling, and%
does not need to be escaped in either.sprintf
takes a string with doubled%
to indicate%
, but that's not related to building strings and regex patterns.您还可以使用
index()
等字符串函数检查“%”是否在字符串内You can also check if "%" is inside your string using string functions such as
index()