[英]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 (ie: letter number or underscore). 使用ruby正则表达式,如何匹配用逗号分隔的列表中的所有单词,但是仅当整个单词包含有效的单词字符(即:字母数字或下划线)时才匹配。 For instance, given the string:
例如,给定字符串:
"see, jane, run, r#un, j@ne, r!n"
“看,简,奔跑,r#un,j @ ne,r!n”
I would like to match the words 我想匹配的话
'see', 'jane' and 'run',
'see','jane'和'run',
but not the words 但不是话
'r#un', 'j@ne' or 'r1n'.
“ r#un”,“ j @ ne”或“ r1n”。
I do not want to match the coma ... just the words themselves. 我不想匹配昏迷...只是单词本身。
I have started the regex here: http://rubular.com/regexes/12126 我在这里开始了正则表达式: 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"]
其他方式
result = s.split(/[\\s,]/).select{|_w| _w =~ /^\\w+$/}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.