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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效