开发者

Conditional regex for URL formatting

Looking for an efficient regex to do this

/url-example-123.shtml & /url-example-25.shtml

开发者_开发百科

to /url-example-3

Objectives:

  1. remove the .shtml

  2. replace with 3 if the numbers are between 25 and 125


Since you didn't give a language I can only give you a regex. You can use the following to match numbers between 25 & 125: (?:(?:1[0-1][0-9])|(?:12[0-5]))|(?:[^\d](?:2[5-9])|(?:[^\d](?:[3-9][0-9]))). You can then just do a replace with that match and a 3. If there will always be a .shrml at the end then you could add that to the end of the expression.


The question is vague. Not sure what should happen if there is no number, or if the number is outside the given range. Now that you've specified PHP, I've edited my answer:

echo preg_replace(
  "/(?<=\/url-example-)(2[5-9]|[4-9][0-9]|1[01][0-9]|12[0-5]).shtml/",
  "3",
  myUrl);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜