Rotem B
Rotem B

Reputation: 1377

Regular expression not worknig

I am trying to create a regular expression in javascript with the following rules:

  1. At least 2 characters.
  2. Should have at least 1 letter as a prefix and end with a . or have or - 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

Answers (1)

Mustofa Rizwan
Mustofa Rizwan

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]|\.)$

Explanation

1st Alternative ^[a-zA-Z][a-zA-Z]*[ -][a-zA-Z]*[a-zA-Z]$

  1. ^ asserts position at start of a line
  2. [a-zA-Z] Match a single character present in [a-zA-Z]
  3. [a-zA-Z]* * Quantifier — Matches between zero and unlimited times(greedy)
  4. [ -] Match a single character - or a space
  5. $ asserts position at the end of a line

2nd Alternative ^[a-zA-Z][a-zA-Z]*([a-zA-Z]|\.)$

  1. ^ asserts position at start of a line

  2. [a-zA-Z] Match a single character present in [a-zA-Z]

  3. [a-zA-Z]* * Quantifier — Matches between zero and unlimited times(greedy)
  4. ([a-zA-Z]|.) Match a single character present in the list below [a-zA-Z] or dot
  5. $ asserts position at the end of a line

Upvotes: 3

Related Questions