sub:允许在 2 个字母数字之间使用可选连字符并限制空格的模式。没有其他特殊字符
我需要一个正则表达式来匹配以下测试用例:-
"all-owed" "allowe-d" "a-llo-wed-12" "allowed12" "allow-12ed" "allowed-12" "allo-wed-12"
"not allowed" "not allowed " " notallowed" " nota-llowed" "not--allowed" "not@allowed"
尝试过的模式:
^[^-]*-?[^-]*$
^\\w+(-\\w+)*$
javascript regex for special characters
Java regex - alphanumeric, at most one hyphen, period or underscore, seven characters long
PHP regex to match alphanumeric and hyphens (not spaces) for use as subdomain
还有更多
请发布重复的问题链接。我们可以从那里提供的解决方案中学习并改进我们的搜索
最佳答案
你的第二个正则表达式 ^\w+(-\w+)*$
会匹配您的大小写,但 \w
也会匹配下划线。
也许您正在寻找一种与字母数字 [a-z0-9]+
匹配一次或多次的模式,然后重复匹配破折号,后跟与字母数字 匹配一次或多次>(?:-[a-z0-9]+)*
请注意,这仅匹配小写字符。您可以使用不区分大小写的标志来匹配大写和小写字符。
const strings = [
"all-owed",
"allowe-d",
"a-llo-wed-12",
"allowed12",
"allow-12ed",
"allowed-12",
"allo-wed-12",
"notallo-wed-12_",
"not allowed",
"not allowed ",
" notallowed",
" nota-llowed",
"not--allowed",
"not@allowed"
];
let pattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});
关于javascript - 允许在 2 个字母数字之间使用可选连字符并限制空格的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063724/