Reputation: 697
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
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:
(.+?)
needs 22 steps for the given 343dds
key(.+?)
needs 68 steps for a longer key like thisIsASignificativelyLongKey
([^-]+)
needs 12 steps only for any keyUpvotes: 2
Reputation: 317
The (.+)
is being greedy and matching the rest of the input. Change it to (.+?)
to make it not greedy.
Upvotes: 6