Question: I want to check that my string only contains numbers, spaces and the following special chars: 

```
[ ] , 

```

I tried the following from "[How to check string contains special character in ruby](https://stackoverflow.com/questions/6343257/how-to-check-string-contains-special-character-in-ruby)":

```
special = "1234567890[], "
regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/ 
test1 = [1,2,[3,4],5].to_s
test2 = ["a",2,[3,4],5].to_s

```

When running these, they both return "fail":

```
puts "fail" if test1 =~ regex
puts "fail" if test2 =~ regex

```

Can anyone help on this?

Answer: 
Try this

```
your_string.match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)

```

I've tried this

```
2.2.2 :033 > "123a1231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)
 => nil 
2.2.2 :034 > "1231231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)
 => #<MatchData "1231231,2]" 1:"]"> 
2.2.2 :035 > "12.31231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)
 => nil 
2.2.2 :036 > "aa1231231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)
 => nil 
2.2.2 :037 > "12[31231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/)
 => #<MatchData "12[31231,2]" 1:"]"> 
2.2.2 :038 > "12[31231,2]".match(/^([[:digit:]]|\]|[[:space:]]|\[|\,)*$/).to_s
 => "12[31231,2]" 
2.2.2 :039 > 

```
You can use

```
regex = /\A[\[\],\p{Zs}\p{N}]+\z/

```

See [demo](http://rubular.com/r/iiwagjSfEl) (note that `\A` and `\z` are replaced with `^` and `$` for demo purpose to match the whole line, not string).

Also, here is an [IDEONE demo](http://ideone.com/hujLFW).

The regex matches:

* `\A` - Start of string
* `[\[\],\p{Zs}\p{N}]+` - 1 or more characters that are either `[` or `]` or a comma, or a space (`\p{Zs}`) or a digit (`\p{N}`).
* `\z` - end of string

**Why not `\A(\[|\]|,|\p{Zs}|\p{N})+\z`?** In case we use alternatives, the number of backtracking steps increases, and with very long string ends up in catatrophic backtracking quicker. In other words, it decreases performance.

**Why not `^`/`$`?** In Ruby, `^` matches at the beginning of a line, not the whole string. Same with `$`, it matches the end of the line, not the end of the string.