Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select any number of digits with regex?

Tags:

regex

I'm trying to write a regex that will extract the numbers after directory/ in the following URL:

http://www.website.com/directory/9892639512/alphanum3r1c/some-more-text-here/0892735235

If I know the number of digits, then this regex I wrote works:

directory\/([0-9]{7})\/

However, if I remove the number of digits to match {7}, then the regex stops working.

Live demo: http://regex101.com/r/wX3eI2

I've been trying different, things, but can't seem to get the regex to work without explicitly setting the number of characters to match.

How can I get this working?

like image 969
Nate Avatar asked Jan 12 '14 19:01

Nate


People also ask

How do I select a number in regex?

\d for single or multiple digit numbers It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range. [1-9][0-9] will match double digit number from 10 to 99.

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.

How does regex Match 5 digits?

match(/(\d{5})/g);

How does regex match 4 digits?

Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.


1 Answers

Change regex to:

directory\/([0-9]+)\/

The {7} means, 7 characters (in this case only numbers). The + means one or more characters (in this case numbers).

like image 155
Niels Avatar answered Oct 17 '22 03:10

Niels