doujia1163 2016-02-24 14:55
浏览 15
已采纳

正则表达式问题用于字符串验证

I am trying to validate following type of string using regular expressions in PHP. Using PHP 5.5.9.

String is in following format:

/[sometext]/course/[sometext1]/[sometext2]

What I need is a regex that will accept string that is only in that format and nothing else. Meaning these would be invalid:

/aaa/course/bbb/ccc/
/aaa/course/bbb/ccc/ddd

What I have so far is this:

/\/(?P<domain>.+?)\/course\/(?P<courseid>.+?)\/(?P<reportname>.+?)/

Any ideas?

Update:

With the help from all posters and especially wiktor-stribi%c5%bcew I got this one that works:

 $regex = '#^/(?P<domain>[^/]+)/course/(?P<courseid>[^/]+)/(?P<reportname>[^/]+)$#';
  • 写回答

2条回答 默认 最新

  • dpp78272 2016-02-24 15:01
    关注

    You can use the following regular expression:

    ^\/(?P<domain>[^\/]+)\/course\/(?P<courseid>[^\/]+)\/(?P<reportname>[^\/]+)$
    

    PHP:

    $re = '~^/(?P<domain>[^/]+)/course/(?P<courseid>[^/]+)/(?P<reportname>[^/]+)$~';
    

    See the regex demo

    The [^\/] is a negated character class that matches any character but /.

    The ^ and $ are usually enough to make sure your input starts and ends with the current pattern (you can replace them with \A and \z respectively to make sure the \z matches at the very end of the string, or use ^/$ with the /D modifier).

    Even if you use lazy .+? dot matching, the . can overflow several / delimiters if it is necessary to return a valid match.

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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写