douchai7891 2017-05-10 08:46
浏览 23
已采纳

如何防止[a-z]类型的正则表达式匹配控制字符

recently I've been using [a-z] class range regexp in php. I don't know why, but instead of matching only a to z chars, it also matches control characters. Exemple:

preg_match("#^[a-z]{0,3}$#", "aa
")

is returning 1. (I'm on php 5.6). I would like to prevent the controls characters matched. I've done a few tests with [:^cntrl:] without much succcess. Could someone help me please. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanbarong4321 2017-05-10 08:51
    关注

    The $ anchor may match at the end of the string, or before a final newline in a string.

    Use a /D PCRE_DOLLAR_ENDONLY modifier:

    preg_match("#^[a-z]{0,3}$#D", "aa
    ")
                             ^
    

    Or \z anchor that matches at the very end of the string:

    preg_match("#^[a-z]{0,3}\z#", "aa
    ")
    

    PHP test:

    echo preg_match("#^[a-z]{0,3}$#", "aa
    ");  // => 1
    echo preg_match("#^[a-z]{0,3}$#D", "aa
    "); // => 0
    echo preg_match("#^[a-z]{0,3}\z#", "aa
    "); // => 0
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染