ruby - Check if string contains only permitted characters -


the task: identifiers must contain @ least 1 non-digit , contain digit, letter, "_", , "-" characters.

therefore 'qwerty', 'identifier-45', 'u_-_-', '-42-' valid identifiers.

and '123456', 'w&1234', 'identifier 42' invalid.

can achieve regular expression.

id.match(/\w\d/) 

or more 1 match

id.match(/\w/) &&  id.match(/\d/) 

or may make array of permitted characters , filter original string removing them (if rest more [], there forbidden ones)?

id.to_a.select{|character| !((0..9) + (a..z) + ['-','_']).include?(character)}.count == 0 

i.e. permitted characters excluded string, , if length more 1, there forbidden characters (like &)

using positive lookahead:

pattern = /^(?=.*\d)[-\w]+$/  pattern =~ 'qwerty' # => 0 pattern =~ 'identifier-45' # => 0 pattern =~ 'u_-_-' # => 0 pattern =~ '-42-' # => 0  pattern =~ '123456' # => nil pattern =~ 'w&1234' # => nil pattern =~ 'identifier 42' # => nil 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -