Reputation: 29777
How can I write a regex in Ruby 1.9.2 that will determine if a string meets this criteria:
-
characterUpvotes: 2
Views: 144
Reputation: 80065
No regex:
str.count("a-zA-Z") > 0 && str.count("^a-zA-Z0-9-") == 0
Upvotes: 1
Reputation: 12245
I suppose these two will help you: /\A[a-z0-9\-]{1,}\z/i
and /[a-z]{1,}/i
. The first one checks on first two rules and the second one checks for the last condition.
Upvotes: 1
Reputation: 15954
/\A[a-z0-9-]*[a-z][a-z0-9-]*\z/i
It goes like
Upvotes: 4
Reputation: 52185
You can take a look at this tutorial for how to use regular expressions in ruby. With regards to what you need, you can use the following:
^[A-Za-z0-9\-]+$
The ^
will instruct the regex engine to start matching from the very beginning of the string.
The [..]
will instruct the regex engine to match any one of the characters they contain.
A-Z mean any upper case letter, a-z means any lower case letter and 0-9 means any number.
The \-
will instruct the regex engine to match the -
. The \
is used infront of it because the -
in regex is a special symbol, so it needs to be escaped
The $
will instruct the regex engine to stop matching at the end of the line.
The +
instructs the regex engine to match what is contained between the square brackets one or more time.
You can also use the \i
flag to make your search case insensitive, so the regex might become something like this:
^[a-z0-9\-]+/i$
Upvotes: 0