我是正则表达式和 typescript 的新手,正在尝试让正则表达式匹配:
1. must start with alphanumeric (repeating is fine)
2. can contain alphanumeric (repeating is fine)
3. can contain periods, underscores, and/or hyphens (no repeating)
4. must end with alphanumeric (repeating is fine)
我一直在搜索,发现了许多类似的示例,并且我尝试调整它们以根据需要工作,但是我一直无法找到正确的解决方案。如果有人有一个很好的正则表达式可以提供帮助,并且可以解释原因,那么我就可以了解更多关于该系统的信息,那就太棒了。
以下是我尝试验证为可接受字符串的一些示例:
this.is.Valid
also_a_valid_1
Me-too.im_an-ugly.but_vALid-5tring
以及我当前的正则表达式允许的无效字符串的一些示例,但应该会失败,因为它有重复的句点/连字符/下划线,并且在开始和结束处有句点、连字符、下划线:
-this..should..not.be.valid....
..THIS__.-also-should..fail-
why..IS_regex--so.confusing-for-n0obs
这是我正在使用的正则表达式的示例:
validateString(myString: string): boolean {
return (/^[a-zA-Z0-9_\-\.]+((\.-?|-\.?)[a-zA-Z0-9_\-\.]+)*$/.test(varKey))
}
最佳答案
使用:
^[a-z0-9]+(?:[._-][a-z0-9]+)*$
解释:
^ # beginning of line
[a-z0-9]+ # 1 or more alphanum
(?: # start non capture group
[._-] # period, underscore or hyphen
[a-z0-9]+ # 1 or more alphanum
)* # end group, may appear 0 or more times
$
var test = [
'this.is.Valid',
'also_a_valid_1',
'Me-too.im_an-ugly.but_vALid-5tring',
'-this..should..not.be.valid....',
'..THIS__.-also-should..fail-',
'why..IS_regex--so.confusing-for-n0obs',
'h',
'sTrInG',
];
console.log(test.map(function (a) {
return a+' :'+/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/i.test(a);
}));
关于正则表达式仅匹配字母数字、连字符、下划线和句点,没有重复的标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57528962/