user1086010
user1086010

Reputation: 697

Regex Extract ID From URL

I have url like this domain.com/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.

Upvotes: 1

Views: 2916

Answers (2)

cFreed
cFreed

Reputation: 4474

Jeremy Hanlon's solution obviously works but is not the most recommended 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:

Upvotes: 2

Jeremy Hanlon
Jeremy Hanlon

Reputation: 317

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

Upvotes: 6

Related Questions