EngMyWorld
EngMyWorld

Reputation: 19

Regex starts with alphabet or underscore (_)

I'm trying to check string starting with underscore(_) or alphabet and can contain only letters, digits, hyphens, underscores or periods. The string can also be of length 1.

Expected valid strings:

  1. _Name
  2. _name.First
  3. name-first
  4. Name
  5. name.First
  6. name-first
  7. A
  8. b

I tried using the below given regex but is not working for a single alphabet.

^[a-zA-Z0-9_][a-zA-Z0-9_|/.|/-]{1,20}[a-zA-Z0-9]$

Upvotes: 0

Views: 1556

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18631

Use

^[a-zA-Z0-9_](?:[a-zA-Z0-9_.-]{0,20}[a-zA-Z0-9])?$

See proof.

Explanation

                         EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [a-zA-Z0-9_]             any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9', '_'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    [a-zA-Z0-9_.-             any character of: 'a' to 'z', 'A' to
    ]{0,20}                  'Z', '0' to '9', '_', '.', '-' (between
                             0 and 20 times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    [a-zA-Z0-9]              any character of: 'a' to 'z', 'A' to
                             'Z', '0' to '9'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

Upvotes: 1

Related Questions