tags:

views:

87

answers:

2

Using a ruby regular expression, how do I match all words in a coma separated list, but only match if the entire word contains valid word characters (i.e.: letter number or underscore). For instance, given the string:

"see, jane, run, r#un, j@ne, r!n"

I would like to match the words

'see', 'jane' and 'run',

but not the words

'r#un', 'j@ne' or 'r1n'.

I do not want to match the coma ... just the words themselves.

I have started the regex here: http://rubular.com/regexes/12126

+4  A: 
s="see, jane, run, r#un, j@ne, r!n, fast"
s.scan(/(?:\A|,\s*)(\w+)(?=,|\Z)/).flatten
# => ["see", "jane", "run", "fast"]
glenn jackman
cool, hadn't seen ?: or ?= before
klochner
A: 

another way

result = s.split(/[\s,]/).select{|_w| _w =~ /^\w+$/}

aaz