Mickert
Mickert

Reputation: 23

Regular expression issue in 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.

Upvotes: 2

Views: 2244

Answers (3)

FailedDev
FailedDev

Reputation: 26930

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).

Upvotes: 5

rb512
rb512

Reputation: 6948

You need to enclose forward slashes in ruby.
So your regex should look something like \/\p\/\ this would exactly match /p/
Above posts would help you with the remaining parts

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838216

The hyphen inside a character class means a character range. Escape it to make it a literal hyphen. That is, change this [\w-\/] to [\w\-\/].

Also change [\d+] to \d+ without the square brackets.

Upvotes: 5

Related Questions