Reputation: 11
the output should be like
.test_test1-test - INVALID
test2_test-test. - INVALID
_test.test-test- - INVALID
test.test-test - VALID
test._test-test - INVALID
The current expression that i have is mentioned below
/^[a-zA-Z0-9](?![_.-]?[^\na-zA-Z0-9]{2}).*?[a-zA-Z0-9]$/gim
Upvotes: 0
Views: 1571
Reputation: 11
/^(?!.*\.\.)[a-zA-Z0-9_-](?:[a-zA-Z0-9_.-]{0,62}[a-zA-Z0-9_-])?$/
This expression worked with all the scenarios mentioned.
Upvotes: 0
Reputation:
If the conditions are applied to the entire string first, it ends up like this :
/^(?![._-])(?!.*[._-]$)(?!.*[._-][._-])[\w.-]*$/
https://regex101.com/r/hnVimE/1
Explained
^ # BOS
(?! [._-] ) # Not . or _ or - at beginning
(?! .* [._-] $ ) # Not . or _ or - at end
(?! .* [._-] [._-] ) # No consecutive . or _ or -
[\w.-]* # Not special characters, except . or _ or -
$ # EOS
This is set to match the empty string [\w.-]*
, set the quantifier to +
if text is a requirement also.
Upvotes: 0
Reputation: 9313
You could also use:
^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$
and then negate the result:
rg = new RegExp('^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$','gim')
!rg.test('test.test-test')
Examples:
rg = new RegExp('^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$','gim')
console.log('Valid')
console.log('test.test-test', !rg.test('test.test-test'))
console.log('Invalid')
console.log('.test.test-test', !rg.test('.test.test-test'))
More examples here
Upvotes: 0
Reputation: 8670
Your regex seams to be a little bit complicated for what you are trying to do.
You have two part to your regex:
test
plus a symbole, that repeat twice.test
but no symbol, that end the regex.Also, you don't need to validate A-Z
in your match group since your regex has an case insencitive flag.
Here is a working example :
/^([a-z0-9]+[._-]?){2}([a-z0-9]+)$/gmi
You can test more cases here
Upvotes: 1
Reputation: 30995
I can come up with a regex like this:
^[a-z]+(?:-[a-z]+)*(?:\.[a-z]+(?:-[a-z]+)*)+$
However, this will generate a lot of backtracking and it will be slow if strings are long
I think the best solution for you is to split the string by .
and then validate that each string matches the pattern of ^[a-z]+(?:-[a-z]+)*$
Upvotes: 2