dongou4052 2011-07-25 23:58
浏览 64
已采纳

php正则表达式为4个字符

I am trying to construct a regular expression for a string which can have 0 upto 4 characters. The characters can only be 0 to 9 or a to z or A to Z.

I have the following expression, it works but I dont know how to set it so that only maximum of 4 characters are accepted. In this expression, 0 to infinity characters that match the pattern are accepted.

'([0-9a-zA-Z\s]*)'
  • 写回答

4条回答 默认 最新

  • dongzhi8487 2011-07-26 09:30
    关注

    If you want to match a string that consists entirely of zero to four of those characters, you need to anchor the regex at both ends:

    '(^[0-9a-zA-Z]{0,4}$)'
    

    I took the liberty of removing the \s because it doesn't fit your problem description. Also, I don't know if you're aware of this, but those parentheses do not form a group, capturing or otherwise. They're not even part of the regex; PHP is using them as regex delimiters. Your regex is equivalent to:

    '/^[0-9a-zA-Z]{0,4}$/'
    

    If you really want to capture the whole match in group #1, you should add parentheses inside the delimiters:

    '/(^[0-9a-zA-Z]{0,4}$)/'
    

    ... but I don't see why you would want to; the whole match is always captured in group #0 automatically.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分