'Need regex which accept only 4 alpha numeric words and accept period, hyphen and underscore in between
I am trying to write a regex to accept only 4 words and in between the words accept special characters like period(.), hyphen(-) and underscore(). Also if I use hyphen (-) or underscore () between the words then it is going to be considered as one word. For ex: a_b.c.d.e --> Here the word length is 4 as a_b is considered as 1 word. a.b-c.d.e --> Still it is 4 words as b-c should be considered as 1 word.
The special characters can't be the same immediately before the next word (means no duplicate spl chars immd).
Also I want this regex to accept only lowercase alphabets and numbers. The accepted pattern examples are as below.
Valid cases
- a.b.c.d
- a-b.c.d.e
- a_b.c.d.e
- a.b-c.d.e
- a.b_c.d.e
Invalid cases
- a..b.c.d.e
- a--b.c.d.e 3.a__b.c.d.e
- a_b.c.d
- a-b.c.d
I tried the below regex and it works upto some extent.
^[a-z0-9]+(?:[._-][a-z0-9]+)*$
The above one is failing in scenarios like
- if I provide more than 4 words.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|