views:

521

answers:

7

How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter
it must end with a letter
it can contain a dash (minus sign), but not at start or end of the expression

+1  A: 
^[a-zA-Z]+-?[a-zA-Z]+$

E.g.

def validate(whatever)
  reg = /^[a-zA-Z]+-?[a-zA-Z]+$/
return (reg.match(whatever)) ? true : false;
end
A: 

This regular expression matches sequences, that consist of one or more words of letters, that are concatenated by dashes.

^[a-zA-Z]+(?:-[a-zA-Z]+)*$
Gumbo
A: 

xmammoth pretty much got it, with one minor problem. My solution is:

^[a-zA-Z]+\-?[a-zA-Z]+$

Note that the original question states, it can contain a dash. The question mark is needed after the dash to make sure that it is optional in the regex.

Nik Reiman
But the backslash before the dash is not needed.
Gumbo
A: 
^[A-Za-z].*[A-Za-z]$

In other words: letter, anything, letter.

Might also want:

^[A-Za-z](.*[A-Za-z])?$

so that a single letter is also matched.

Douglas Leeder
A: 
/^[A-Za-z]+(-?[A-Za-z]+)?$/

this seems like what you want.

^ = match the start position
^[A-Za-z]+ = start position is followed by any at least one or more letters.
-? = is there zero or one hyphens (use "*" if there can be multiple hyphens in a row).
[A-Za-z]+ = hyphen is followed by one or more letters
(-?[A-Za-z]+)? = for the case that there is a single letter.
$= match the end position in the string.

gnomed
A: 

What I meant, to be able to create tags. For example: "Wild-things" or "something-wild" or "into-the-wild" or "in-wilderness" "my-wild-world" etc...

You can edit your post. Open up the post and click on "edit" below and to the left of the question.
Brian
A: 

Well,

[A-Za-z].*[A-Za-z]

According to your rules that will work. It will match anything that:

  • starts with a letter
  • ends with a letter
  • can contain a dash (among everything else) in between.
dreamlax