Reputation: 3
I need a regular expression that match exactly 1-12 and 1-31. 01 is not matched and 65 is not matched. For example "abc 6 abc" is a match, while "abc 65 "is not.
I try this /[1-9]|1[012]/
, which does not work.
Upvotes: 0
Views: 90
Reputation: 13911
In my opinion this is not a job for a single regexp. Would it not be hard to understand this code when you look back to it in a few years? Why not split it up in two parts?
my_string = 'abc 01 def'
my_string2 = 'abc 8 def'
p ('1'..'12').include?(my_string[/\d+/]) #=> false
p ('1'..'12').include?(my_string2[/\d+/]) #=> true
Upvotes: 0
Reputation: 174706
You need to add word boundaries around your pattern . \b
matches between a word character and a non-word character.
For 1-12
/\b(?:1[012]|[1-9])\b/
For 1-31
\b(?:[12]\d|3[01]|[1-9])\b
Upvotes: 1