I have a regular expression
/\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
and i want to check if various years are present.
"2003" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns 0 as expected
"2010" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns nil as expected
But i want only exact matches so when i search for "2003 - 2008" i want
nil returned as there is no exact match for that particular string. I
thought the \b would give me this but it doesnt.
To do exactly what you are asking for: you can anchor the regexp
to the beggining or end of the string:
irb(main):013:0> re = /\A(2003|2004|2005|2006|2007|2008|2009)\Z/
=> /\A(2003|2004|2005|2006|2007|2008|2009)\Z/
irb(main):014:0> "2003" =~ re
=> 0
irb(main):015:0> "2003 - 2008" =~ re
=> nil
In this case you don't need the \b anymore. BTW, you had typos there
because you had \2 instead of \b.
Anyway, if you want exact matches of strings you don't need regexps:
If you have many numbers and many lookups, a Set should be better,
performance-wise.
Now, if we are talking about ranges of years we can do even better:
On Thu, Nov 20, 2008 at 1:49 PM, John Butler <johnnybutler7@gmail.com> wrote:
Hi,
I have a regular expression
/\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
and i want to check if various years are present.
"2003" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns 0 as expected
"2010" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns nil as expected
But i want only exact matches so when i search for "2003 - 2008" i want
nil returned as there is no exact match for that particular string. I
thought the \b would give me this but it doesnt.
I have a regular expression
/\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
and i want to check if various years are present.
"2003" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns 0 as expected
"2010" =~ /\b2003|\2004|\2005|\2006|\2007|\2008|\2009\b/
returns nil as expected
But i want only exact matches so when i search for "2003 - 2008" i want
nil returned as there is no exact match for that particular string. I
thought the \b would give me this but it doesnt.
To do exactly what you are asking for: you can anchor the regexp
to the beggining or end of the string:
irb(main):013:0> re = /\A(2003|2004|2005|2006|2007|2008|2009)\Z/
=> /\A(2003|2004|2005|2006|2007|2008|2009)\Z/
irb(main):014:0> "2003" =~ re
=> 0
irb(main):015:0> "2003 - 2008" =~ re
=> nil
I'd rather use /\A200[3-9]\z/.
In this case you don't need the \b anymore. BTW, you had typos there
because you had \2 instead of \b.
Anyway, if you want exact matches of strings you don't need regexps: