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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大