'how to match a group of word and hypen characters with a separator that can occur zero or n times?

My regex to match the below pattern doesn't work . Please can you let me know where I am going wrong?

I can have groups of word characters and hyphen separated by zero to four dots

[\w-]*(\.\w*)?\.\w*\.\w*\.\w*

SOME EXAMPLES ARE AS BLEOW

A.B.C.D.E
A
A.B
A-B.C
A_B-C.D.E
A.B-C.D.E
A.B.C_D-E.F
A.B.C


Solution 1:[1]

You may use this regex for matching these combinations:

^\w+(?:\.\w+){0,4}(?:-\w+(?:\.\w+){0,4})?$

RegEx Demo

RegEx Details:

  • ^: Start
  • \w+: Match 1+ word characters
  • (?:\.\w+){0,4}: Match 0 or 4 words separated by a dot
  • (?:: Start non-capture group
    • -: Match a hyphen
    • \w+: Match 1+ word characters
    • (?:\.\w+){0,4}: Match 0 or 4 words separated by a dot
  • )?: End non-capture group. ? makes it an optional group
  • $: End

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anubhava