Home > Net >  how can I limit dot only once or optional in regex
how can I limit dot only once or optional in regex

Time:06-16

A regex is needed which should have only special character dot which should either be optional or occur only once.

pattern = /^([A-Za-z.] )$/;

CodePudding user response:

Without more information I'd use

/^(?!$)[a-z]*\.?[a-z]*$/i

The negative lookahead prevents empty matches.

See this demo at regex101

CodePudding user response:

Here are some ways to do it:

  1. Deal separately where the input has has one dot, with optional letters surrounding it, or no dot (but then having at least one letter):

    /^([a-z]*\.[a-z]*|[a-z] )$/i

  1. Just capture letters and dots like you did, but don't allow the input to have two dots, using a negative look ahead:

    /^(?!(.*\.){2})([a-z.] )$/i

  2. Capture optional letters then an optional point and then optional letters, but forbid an empty input with a negative look-ahead:

    /^(?!$)([a-z]*\.?[a-z]*)$/i

  • Related