[英]Regex to not allow '.', '_', '-' at String Start or End and should not have consecutive '.' and the rest all special characters should not be allowed
輸出應該像
.test_test1-test - INVALID
test2_test-test. - INVALID
_test.test-test- - INVALID
test.test-test - VALID
test._test-test - INVALID
下面提到了我目前的表達方式
/^[a-zA-Z0-9](?![_.-]?[^\na-zA-Z0-9]{2}).*?[a-zA-Z0-9]$/gim
我可以想出一個這樣的正則表達式:
^[a-z]+(?:-[a-z]+)*(?:\.[a-z]+(?:-[a-z]+)*)+$
但是,這會產生很多回溯,如果字符串很長,它會很慢
我認為對您來說最好的解決方案是將字符串拆分為.
然后驗證每個字符串是否與^[az]+(?:-[az]+)*$
的模式匹配
對於您要執行的操作,您的正則表達式接縫有點復雜。
你的正則表達式有兩部分:
test
加上一個符號,重復兩次。test
但沒有符號,結束正則表達式。 此外,您不需要在匹配組中驗證AZ
,因為您的正則表達式具有不區分大小寫的標志。
這是一個工作示例:
/^([a-z0-9]+[._-]?){2}([a-z0-9]+)$/gmi
您可以在這里測試更多案例
如果先將條件應用於整個字符串,則結果如下:
/^(?![._-])(?!.*[._-]$)(?!.*[._-][._-])[\\w.-]*$/
https://regex101.com/r/hnVimE/1
解釋
^ # BOS
(?! [._-] ) # Not . or _ or - at beginning
(?! .* [._-] $ ) # Not . or _ or - at end
(?! .* [._-] [._-] ) # No consecutive . or _ or -
[\w.-]* # Not special characters, except . or _ or -
$ # EOS
這設置為匹配空字符串[\\w.-]*
,將量詞設置為+
如果文本也是一個要求。
您還可以使用:
^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$
然后否定結果:
rg = new RegExp('^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$','gim')
!rg.test('test.test-test')
例子:
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'))
更多例子在這里
/^(?!.*\.\.)[a-zA-Z0-9_-](?:[a-zA-Z0-9_.-]{0,62}[a-zA-Z0-9_-])?$/
這個表達式適用於所有提到的場景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.