1

I have just started learning JS. In the regular expressions topic, as one of my assignments, this was the problem statement.

The string can have the following characters-

Uppercase (A-Z) and lowercase (a-z) English letters.

Digits (0-9).

Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~

Character . dot provided that it is not the first or last character and it will not come one after the other.

I tried many different ways and the best I could do was - /^[^.]([\^><@,.]+)/

It is clearly wrong. The main issue for me is ensuring that the .(dot) does not come in the beginning or the end and it does not repeat. There are other issues as well.

can someone give me a help with it?

Vivek
  • 75
  • 8
  • Use a negative lookahead at beginning and state that matching a period shouldn't follow another period with the same technique. Also you never mentioned that `.` should be matched. Try `^(?!\.)(?:[A-Za-z0-9!#$%&'*+\/=?^_{|}~-]+|\.(?!\.))+$` – revo Mar 19 '19 at 12:56
  • When you use `.` (dot) as a regular character in RegEx you need to escape it. See https://stackoverflow.com/questions/13989640/regular-expression-to-match-a-dot/25228071 – PM 77-1 Mar 19 '19 at 12:58

1 Answers1

0

A negative lookahead at beginning ensures that dot never occurs at start of input string and to reject consecutive periods or a period at the end an expression like \.(?!\.|$) will do the job:

^(?!\.)(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~-]+|\.(?!\.|$))+$

See live demo here

revo
  • 47,783
  • 14
  • 74
  • 117