douxia1988 2015-03-11 02:49
浏览 58
已采纳

PHP正则表达式:字符串必须包含X个字符N次

I'm newbie in the world of regular expression.
I want to create an expression can match X character N times in a string.
for example:

X = t

N = 2

then it should match string test or tit or tt.

  • 写回答

2条回答 默认 最新

  • dongmei8760 2015-03-11 03:19
    关注

    Solution using RegEx

    /^([^t]*t[^t]*){2}$/
    

    Where N = 2

    • ^ Anchors the regex at the start of the string.

    • [^t]* Negated character class, matches anything other than t. * Quntifies it any number of times

    • t Which is followed by a t

    • [^t]* Further followed by anything other than t

    • {2} Quantifies the pattern 2 times. That is it ensures that not t zero or more times followed by t and followed by not t zero or more time. The entire thing must occure 2 times

    • $ Anchors the regex at the end of the string.

    Regex Demo

    Test

    $X='t';
    $N=2;
    
    $regex="/^([^".$X."]*".$X."[^".$X."]*){".$N."}$/";
    
    echo preg_match($regex, "test" );
    // => True
    

    Solution using substr_count

    The substr_count function returns the number of occurence of an substring in a string

    $X='t';
    $N=2;
    if ( substr_count('test', $X ) == $N )
    //The string is ok
    else
    //The string is not ok
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?