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条)

报告相同问题?