admin管理员组

文章数量:1410705

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

本文标签: javascriptRegex Extract ID From URLStack Overflow