正则表达式仅匹配字母数字、连字符、下划线和句点,没有重复的标点符号

标签 regex string typescript

我是正则表达式和 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
$

Demo

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/

相关文章:

regex - PCRE 正则表达式末尾的 i 和 g 是什么意思?

javascript - 没有特定单词的行匹配的正则表达式

c# - 如何获取字符串中尖括号内的子字符串

javascript - 有没有办法为 Typescript 中的嵌套键访问创建类型保护?

Javascript 正则表达式替换换行符

html - 使用正则表达式在 HTML/Js 中获取图像 URL

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?

python3迭代地从字符串中删除第一个字符

Angular 2 : What does variable name with ? 是什么意思?

javascript - cron 作业内的 Promise 未执行