Sumak
Sumak

Reputation: 1051

Regex absolute begginer: filter alphanumeric

I'm playing codewars in Ruby and I'm stuck on a Kata. The goal is to validate if a user input string is alphanumeric. (yes, this is quite advanced Regex)

The instructions:

At least one character ("" is not valid)
Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9
No whitespaces/underscore

What I've tried :

^[a-zA-Z0-9]+$
^(?! !)[a-zA-Z0-9]+$
^((?! !)[a-zA-Z0-9]+)$

It passes all the test except one, here's the error message:

Value is not what was expected

I though the Regex I'm using would satisfy all the conditions, what am I missing ?


SOLUTION: \A[a-zA-Z0-9]+\z (and better Ruby :^) )

(same for beginning: ^ (line) and \A (string), but wasn't needed for the test)

Favourite answer from another player:

/\A[A-z\d]+\z/

Upvotes: 0

Views: 134

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

str !~ /[^A-Za-z\d]/

The string contains alphanumeric characters only if and only if it does not contain a character other than an alphnumeric character.

Upvotes: 0

Emma
Emma

Reputation: 27723

My guess is that maybe, we would start with an expression similar to:

^(?=[A-Za-z0-9])[A-Za-z0-9]+$

and test to see if it might cover our desired rules.

In this demo, the expression is explained, if you might be interested.

Test

re = /^(?=[A-Za-z0-9])[A-Za-z0-9]+$/m
str = ' 
ab
c
def
abc*
def^
'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Upvotes: 1

Related Questions