开发者

How do I match valid words with a ruby regular expression

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


s="see, jane, run, r#un, j@ne, r!n, fast"
s.scan(/(?:\A|,\s*)(\w+)(?=,|\Z)/).flatten
# => ["see", "jane", "run", "fast"]


another way

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜