Reputation: 32645
Like Python? I'm trying to check whether each character in a string is an alphanumeric or not?
Upvotes: 17
Views: 17983
Reputation: 1
there's an easy way to do it:
def isalpha(cstring) # Return true if cstring is a text
if cstring.to_i == 0 && cstring != "0"
lret = true
else
lret = false
end
end
def isnum(cstring) # Return true if cstring is a number
if cstring.to_i == 0 && cstring != "0"
lret = false
else
lret = true
end
end
Upvotes: 0
Reputation: 7956
Here's a way to do it without regex if you have trouble remembering regex (like me!):
def alpha?(char)
char.upcase != char.downcase
end
For any other character than a letter, #upcase
and #downcase
work but have no effect, so we can assert that the char's upcase and downcase values are not equal to determine that it's a letter.
Upvotes: 4
Reputation: 80075
The python function only works for ASCII chars; the [[:alnum]] regex would do things like "tëst".alpha? => true.
match/\w/
matches underscores, so that leaves
def isalpha(str)
return false if str.empty?
!str.match(/[^A-Za-z]/)
end
to reproduce the Python behaviour.
Upvotes: 5
Reputation: 230461
You can roll your own :) Replace alnum
with alpha
if you want to match only letters, without numbers.
class String
def alpha?
!!match(/^[[:alnum:]]+$/)
end
end
'asdf234'.alpha? # => true
'asdf@#$'.alpha? # => false
Upvotes: 20
Reputation: 211670
There's a special character class for this:
char.match(/^[[:alpha:]]$/)
That should match a single alphabetic character. It also seems to work for UTF-8.
To test a whole string:
string.match(/^[[:alpha:]]+$/)
Keep in mind this doesn't account for spaces or punctuation.
Upvotes: 28