如何在Perl中匹配包含特殊字符的3次准确出现的字符串 [英] How to match string that contain exact 3 time occurrence of special character in perl

查看:359
本文介绍了如何在Perl中匹配包含特殊字符的3次准确出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试几种方法来匹配包含正斜杠3倍但不能正常工作的单词.下面是示例

I have try few method to match a word that contain exact 3 times slash but cannot work. Below are the example

@array = qw( abc/ab1/abc/abc a2/b1/c3/d4/ee w/5/a  s/t )
foreach my $string (@array){
    if ( $string =~ /^\/{3}/ ){
          print " yes, word with 3 / found !\n";
          print "$string\n";
    }
    else {
          print " no word contain 3 / found\n";
    }

我尝试的方法很少,但都不起作用

Few macthing i try but none of them work

$string =~ /^\/{3}/;
$string =~ /^(\w+\/\w+\/\w+\/\w+)/;
$string =~ /^(.*\/.*\/.*\/.*)/;

还有其他方法可以匹配此类型的字符串并打印该字符串吗?

Any other way i can match this type of string and print the string?

推荐答案

全局匹配并将匹配数量与3

Match globally and compare the number of matches with 3

if ( ( () = m{/}g ) == 3 ) { say "Matched 3 times" }

其中 =()=运算符是一种玩法在上下文中,将列表上下文强制在其右侧,但是当在其左侧提供标量上下文时,将返回该列表的元素数.

where the =()= operator is a play on context, forcing list context on its right side but returning the number of elements of that list when scalar context is provided on its left side.

如果您对这样的语法扩展感到不舒服,请分配给数组

If you are uncomfortable with such a syntax stretch then assign to an array

if ( ( my @m = m{/}g ) == 3 ) { say "Matched 3 times" }

随后的比较在标量上下文中对其进行评估.

where the subsequent comparison evaluates it in the scalar context.

您尝试匹配三个连续 /,并且您的字符串没有该字符串.

You are trying to match three consecutive / and your string doesn't have that.

这篇关于如何在Perl中匹配包含特殊字符的3次准确出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆