URL 子部分序列中不能只有数字

我想更改正则表达式,以便在类组在两个斜杠之间没有只有数字时匹配:


$regex = "~^upload/(?<class>[/a-z0-9_\.]+)/(?<id_table>\d+)$~";


preg_match($regex, "upload/.bes/.ur/13"); // returns true

preg_match($regex, "upload/.tables/fewf/.u23ser/15"); // returns true

preg_match($regex, "upload/.t/les2/.uer/11"); // returns true

preg_match($regex, "upload/1.tales/.user2/01"); // returns true


preg_match($regex, "upload/23/21"); // returns false

preg_match($regex, "upload/.tables/00/31"); // returns false

preg_match($regex, "upload/6/.uer/q/51"); // returns false


跃然一笑
浏览 166回答 3
3回答

小怪兽爱吃肉

您可以从带有所有格量词的 digit 类开始重写您的命名捕获:(?<class>\d*+[a-z0-9_.]+(?>/\d*+[a-z0-9_.]+)*)由于量词是所有格,您确定匹配的第一个字符[a-z0-9_.]+不是数字。

素胚勾勒不出你

您可以使用$regex&nbsp;=&nbsp;"~^upload/(?<class>(?!\d+/)[a-z0-9_.]+(?:/(?!\d+/)[a-z0-9_.]+)*)/(?<id_table>\d+)$~";请参阅此正则表达式演示。该class组命名模式匹配(?!\d+/)[a-z0-9_.]+&nbsp;- 一个或多个小写 ASCII 字母、数字_或.,但如果所有这些字符都是数字,则不是(?:/(?!\d+/)[a-z0-9_.]+)*&nbsp;- 零次或多次重复/- 一个/字符(?!\d+/)[a-z0-9_.]+- 一个或多个小写 ASCII 字母、数字_或.,但如果所有这些字符都是数字,则不是

慕桂英546537

也许,我们可以用这个表达式来简化它:(\/[0-9]+\/)|([0-9]+$)如果左捕获组返回 TRUE,则为 false,否则为 TRUE。测试$re = '/(\/[0-9]+\/)|([0-9]+$)/m';$str = 'upload/.bes/.ur/13upload/.tables/.u23ser/15upload/.tles2/.uer/11upload/1.tales/.user2/01upload/23/21upload/.tables/00/31upload/6/.uer/51';preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);foreach ($matches as $match) {&nbsp; &nbsp; if (sizeof($match) == 2) {&nbsp; &nbsp; &nbsp; &nbsp; echo "false \n";&nbsp; &nbsp; } elseif (sizeof($match) == 3) {&nbsp; &nbsp; &nbsp; &nbsp; echo "true \n";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; "Something is not right!&nbsp; \n";&nbsp; &nbsp; }}输出true&nbsp;true&nbsp;true&nbsp;true&nbsp;false&nbsp;true&nbsp;false&nbsp;true&nbsp;false&nbsp;true&nbsp;一旦过滤掉不需要的字符串,我们可以简单地捕获这些类:^(upload\/.*?)[0-9]+$
打开App,查看更多内容
随时随地看视频慕课网APP