Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression issue in Ruby

Tags:

regex

ruby

I am trying to extract the below pattern from a string using Ruby and I don't seem to be getting too far on Ruby...

Here is the regex I am using \/p\/[\w-\/]*[\d+]

And here is the type of string I am trying to extract.

/p/hyphenated-words/more-hyphenated-words/102049294

So in short the string always starts with /p/ will end with multiple digits and contain one or more sub directories with possible hyphens.

My regex works on some online expression testers but not in Ruby.

like image 562
Mickert Avatar asked Jun 22 '26 10:06

Mickert


1 Answers

In addition to @Mark Byers answer :

 /p/[\w-/]*[\d+]

The [\d+] part of your regex is irrelevant. The reason is that it is preceded by a greedy quantifier which quantifies a class which in turn contains \w. \w translates into [a-zA-Z0-9_] which will "eat" any digts that come after it.

Finally instead of [\d+] simply use \d (if you must).

like image 77
FailedDev Avatar answered Jun 24 '26 23:06

FailedDev