dongpan1308 2016-02-06 23:35
浏览 34
已采纳

preg_match:/ username或/ username / foo

I'm wanting to preg_match the following URIs. Note usernames are: [\w]{1,15}

/username
/username/foo
/usersname/bar

I want these to fail

/username/anythingelse

The username is mandatory, so the preg_match should work if just a username is given, and then check if anything after is either foo or bar.

preg_match('{^\/([\w]+){1,15}/{/foo|/bar}?$}', $uriString)

You can probably tell my preg_match fails. How may I fix this?

  • 写回答

2条回答 默认 最新

  • dsdsds12222 2016-02-06 23:39
    关注

    Use parentheses to specify a group of alternatives;

    Curly braces are only used to limit repetition {min,max}

    ^\/\w{1,15}(\/foo|\/bar)?$ ==> DEMO

    Above, we allow \w 1 up to 15 times (\w matches any word character [a-zA-Z0-9_])

    Followed by either \/foo or \/bar

    ^ and $ specify the start and the end of the string, meaning that the regex must match the full string not only a part of it

    You can read more about:

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程