Reputation: 1377
I am trying to create a regular expression in javascript with the following rules:
- At least 2 characters.
- Should have at least 1 letter as a prefix and end with a
.
or haveor
-
and then have more letters.
The following strings should be legal - aa
, aaaaa
, a.
, a-a
, a a
.
These should not be legal - a
(too short), aa.aa.
(two dots), aa-
(after -
should be another letter).
I don't know what I'm doing wrong here but my regex doesn't seem to work, as it is legal yet no word matches it:
(?=^.{2,}$)^(([a-z][A-Z])+([.]|[ -][a-zA-Z]+){0,1}$)
Upvotes: 1
Views: 70
Reputation: 10466
Had to re-write it completely to cover op's comment. The new regex would be:
^[a-zA-Z][a-zA-Z]*[ -][a-zA-Z]*[a-zA-Z]$|^[a-zA-Z][a-zA-Z]*([a-zA-Z]|\.)$
1st Alternative ^[a-zA-Z][a-zA-Z]*[ -][a-zA-Z]*[a-zA-Z]$
- ^ asserts position at start of a line
- [a-zA-Z] Match a single character present in [a-zA-Z]
- [a-zA-Z]* * Quantifier — Matches between zero and unlimited times(greedy)
- [ -] Match a single character - or a space
- $ asserts position at the end of a line
2nd Alternative
^[a-zA-Z][a-zA-Z]*([a-zA-Z]|\.)$
^ asserts position at start of a line
[a-zA-Z] Match a single character present in [a-zA-Z]
- [a-zA-Z]* * Quantifier — Matches between zero and unlimited times(greedy)
- ([a-zA-Z]|.) Match a single character present in the list below [a-zA-Z] or dot
- $ asserts position at the end of a line
Upvotes: 3