How to match string that contain exact 3 time occurrence of special character in perl

旧街凉风 提交于 2019-12-02 00:18:14

问题


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?


回答1:


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.




回答2:


The pattern you need (with whitespace added) is

^ [^/]* / [^/]* / [^/]* / [^/]* \z

or

^ [^/]* (?: / [^/]* ){3} \z

Your second attempt was close, but using ^ without \z made it so you checked for string starting with your pattern.


Solutions:

say for grep { m{^ [^/]* (?: / [^/]* ){3} \z}x } @array;

or

say for grep { ( () = m{/}g ) == 3 } @array;

or

say for grep { tr{/}{} == 3 } @array;



回答3:


You need to match

  • a slash
  • surrounded by some non-slashes (^(?:[^\/]*)
  • repeating the match exactly three times
  • and enclosing the whole triple in start of line and and of line anchors:
$string =~ /^(?:[^\/]*\/[^\/]*){3}$/;



回答4:


if ( $string =~ /\/.*\/.*\// and $string !~ /\/.*\/.*\/.*\// )


来源:https://stackoverflow.com/questions/50522918/how-to-match-string-that-contain-exact-3-time-occurrence-of-special-character-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!