javascript - Regex Extract ID From URL - Stack Overflow

I have url like this domainnews-343dds-this-is-test I want to extract news id 343dds,so I tried to us

I have url like this domain/news-343dds-this-is-test

I want to extract news id 343dds, so I tried to use regex

Here is the regex I used /news-(.+)-/

But the result is like this 343dds-this-is. I only want get the 343dds.

I have url like this domain./news-343dds-this-is-test

I want to extract news id 343dds, so I tried to use regex

Here is the regex I used /news-(.+)-/

But the result is like this 343dds-this-is. I only want get the 343dds.

Share Improve this question edited Apr 9, 2016 at 5:31 user663031 asked Apr 9, 2016 at 5:22 user1086010user1086010 6971 gold badge10 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The (.+) is being greedy and matching the rest of the input. Change it to (.+?) to make it not greedy.

Jeremy Hanlon's solution obviously works but is not the most remended one.

You had better using ([^-]+).

Even if it probably doesn't matter in simple cases such as this SO question, the lazy quantifier +? has the inconvenient that the number of steps is proportional to the size of the searched part, so it may widely impact performance.
This is clearly explained here.

Example:

  • (.+?) needs 22 steps for the given 343dds key
  • (.+?) needs 68 steps for a longer key like thisIsASignificativelyLongKey
  • ([^-]+) needs 12 steps only for any key

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745040977a4607803.html

相关推荐

  • javascript - Regex Extract ID From URL - Stack Overflow

    I have url like this domainnews-343dds-this-is-test I want to extract news id 343dds,so I tried to us

    8小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信