doulang9521 2014-05-16 13:48
浏览 20
已采纳

PHP正则表达式特殊字符

I am facing difficulties to validate the below format. I want regular expression needs to be satisfied with the below condition.

$pattern = '/^\w[\w\s\.\%\-\(\)\[\]]*$/u';
$file_name = "(00)filename.jpg";
if(preg_match($pattern,$file_name)){
    echo "Pattern matched";
}else {
    echo "Pattern not matched";
}

I have tried several ways. But, the main problem is do not write the own pregmatch, instead need to modify the existing one which accepts the brackets().

  • 写回答

1条回答 默认 最新

  • douzhan5262 2014-05-16 13:59
    关注

    So this should match (00)filename.jpg and does not, because your regex requires the string to ^\w start with a word-character. You can add optional parenthesized \w+ to the start:

    ^(?:\(\w+\)|\w)[-\w\s.%()[\]]*$
    

    Also need to put the hyphen - at the start or end inside the character class. Else it would express a range. Furthermore need to escape the closing ] inside the character class.

    test at regex101


    But possibly, you just want to check:

    • if there's at least one word-character in the string.
    • the string consist only of [-\w\s.%()[\]]

    If so, use a lookahead to check for the \w:

    ^(?=.*?\w)[-\w\s.%()[\]]+$
    

    test at regex101

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序