tags:

views:

88

answers:

2

I want to match a string that includes the characters 0-9.-,[], something like this:

return true if str =~ /\A[0-9.-,\[\]]*\Z/

Which works except it doesn't seem to match the braces, how do I match those?

+7  A: 

You need to escape the . and - characters:

str =~ /\A[0-9\.\-,\[\]]*\Z/
Michael Sepcot
This will also match an empty string. Change `*` to `+` to make sure the string has at least one character in the set.
Michael Sepcot
"." is not special inside [brackets].
glenn jackman
+3  A: 

turns out it also works w/o escaping the . and - characters like this:

str =~ /\A[\[\]0-9.,-]*\Z/
aaronstacy
Inside a set using square brackets, dot (.) is no longer special. However, dash (-) is unless it is the last character in the set.
tadman