ben
ben

Reputation: 29777

How can I write a regex in Ruby that will determine if a string meets this criteria?

How can I write a regex in Ruby 1.9.2 that will determine if a string meets this criteria:

Upvotes: 2

Views: 144

Answers (4)

steenslag
steenslag

Reputation: 80065

No regex:

str.count("a-zA-Z") > 0 && str.count("^a-zA-Z0-9-") == 0

Upvotes: 1

shybovycha
shybovycha

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

undur_gongor
undur_gongor

Reputation: 15954

/\A[a-z0-9-]*[a-z][a-z0-9-]*\z/i

It goes like

  • beginning of string
  • some (or zero) letters, digits and/or dashes
  • a letter
  • some (or zero) letters, digits and/or dashes
  • end of string

Upvotes: 4

npinti
npinti

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

Related Questions