Home > Blockchain >  Custom Javascript Regex - Cannot make it work
Custom Javascript Regex - Cannot make it work

Time:05-19

I need to accept the following:

  • x{1}.xxxxx{1,40}
  • x{1}.xxxxx{1,40}-xxxxx{1,40}
  • xxxxx{1,40}
  • xxxxx{1,40}-xxxxx{1,40}
  • xxxx xxxxx xxxxx{words with space between}

My regex is not working...

/^([a-z]{1}\.[a-z]{1,40}|[a-z]{1}\.[a-z]{1,40}\-[a-z]{1,40}|[a-z\s]{1,})$/i

While

/^([a-z]{1}\.[a-z]{1,40}|[a-z]{1}\.[a-z]{1,40}\-[a-z]{1,40})$/i

alone is working OK and

/^([a-z\s]{1,})$/i

is working OK as well...

What am I doing wrong? Thank you in advance...

CodePudding user response:

You can try with the following regex:

^(([a-z]\.)?[a-z]{1,40}(-[a-z]{1,40})?|[a-z] ( [a-z] ) )$

This solution uses two patterns:

  • the first one matches your first four samples:
    • optional first group: [a-z]{1}\.
    • mandatory second group: [a-z]{1,40}
    • optional third group: -[a-z]{1,40}
  • the second one matches your last sample:
    • words separated by characters: [a-z] ( [a-z] ) )

These groups will be highlighted separately.

Explanation in detail:

  • ^: start of string
  • ([a-z]\.)?: one alphabetical character dot (optional group)
  • [a-z]{1,40}: from 1 to 40 alphabetical characters
  • (-[a-z]{1,40})?: dash 1 to 40 alphabetical characters (optional group)
  • [a-z] : combination of alphabetical characters
  • ( [a-z] ) : combination of multiple <space combination of characters>
  • $: end of string

Try it here.

CodePudding user response:

You might write the pattern as:

^(?:(?:[a-z]\.)?[a-z]{1,40}(?:-[a-z]{1,40})?|[a-z] (?:\s [a-z] ) )$
  • ^ Start of string
  • (?: Non capture group
    • (?:[a-z]\.)? Match an optional char a-z and a dot
    • [a-z]{1,40} Match 1-40 chars
    • (?:-[a-z]{1,40})? An optional part matching a hyphen and 1-40 chars
    • | Or
    • [a-z] (?:\s [a-z] ) Match 2 or more words with spaces between them
  • ) Close the non capture group
  • $ End of string

See a regex101 demo.

  • Related