dbatten
dbatten

Reputation: 437

How can I check if a string contains only spaces and alphabet letters in Ruby?

How can I check if a string contains only spaces and alphabet letters?

I'm not sure about how to implement it into my code. At the moment I have

phrase.match(/[[:alpha:]]+[[:blank:]]/)

which I thought would return true if the phrase contains only alphabet letters and spaces but this isn't working. Any help would be greatly appreciated.

Upvotes: 2

Views: 5248

Answers (3)

Timmy
Timmy

Reputation: 251

Avinash Raj provided almost correct answer, so I'll just build up on that.

Just combine the both char classes. And the anchors are much needed here.

phrase.match(/\A[[:alpha:][:blank:]]+\z/)

Example:

"ds ds sd ds".match(/\A[[:alpha:][:blank:]]+\z/)
=> #<MatchData "ds ds sd ds">

"dad56".match(/\A[[:alpha:][:blank:]]+\z/)
=> nil

"sdfd Ajds".match(/\A[[:alpha:][:blank:]]+\z/)
=> #<MatchData "sdfd Ajds">

"sdfd Ajds".match(/\A[[:alpha:][:blank:]]+\z/)
=> #<MatchData "sdfd Ajds">

"hghds /*".match(/\A[[:alpha:][:blank:]]+\z/)
=> nil

"abcd def SURPRISE".match(/\A[[:alpha:][:blank:]]+\z/)
=> #<MatchData "abcd def SURPRISE">

"abcd def\nSURPRISE".match(/\A[[:alpha:][:blank:]]+\z/)
=> nil

Upvotes: 1

sawa
sawa

Reputation: 168101

Use negative match.

phrase !~ /[^[:alpha:][:blank:]]/

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Just combine the both char classes. And the anchors are much needed here.

phrase.match(/^[[:alpha:][:blank:]]+$/)

This would find a match only if the input string contain letters or spaces.

DEMO

Upvotes: 6

Related Questions