Reputation: 762
I need to match a url path with that contain any of 2 words vendor_tracks or shop_types, but shop types should be followed by a ' / '
My current REGEX is
//(vendor_tracks|shop_types)/
, but this match if contain shop_types/22
I need my Regex to match something like :
/shop_types?q%5Btrack_department
but NOT the below url
/shop_types/27/list_pinned_vendors
My current accepts both, while I need it to accept only the first. I tried many different methods to exclude the "shop_types" followed by / but always get escaped backslash error. Any solution for this? or alternative REGEX
Upvotes: 2
Views: 364
Reputation: 23667
You can use lookarounds to create custom restrictions
>> str1 = '/shop_types?q%5Btrack_department'
=> "/shop_types?q%5Btrack_department"
>> str2 = '/shop_types/27/list_pinned_vendors'
=> "/shop_types/27/list_pinned_vendors"
>> str1.match?(/shop_types(?!\/)/)
=> true
>> str2.match?(/shop_types(?!\/)/)
=> false
Here (?!\/)
is negative lookahead which says that /
character cannot be immediate character after shop_types
Note that end of string will also satisfy this condition as that would imply that there is no /
character after shop_types
I tried many different methods to exclude the "shop_types" followed by / but always get escaped backslash error
You can use %r
to define a regexp with alternate delimiters
# here the condition has also been changed
# restriction is that / shouldn't occur anywhere after matching shop_types
>> str1.match?(%r{shop_types(?!.*/)})
=> true
>> str2.match?(%r{shop_types(?!.*/)})
=> false
Upvotes: 2