且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式匹配以'-'分隔的字母数字单词

更新时间:2022-11-12 08:44:52

尝试一下:

/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/

这将仅匹配由单个-分隔的一个或多个字母数字字符序列.如果您不想允许单个单词(例如,只是 hello ),请用 + 替换 * 乘数,以仅重复一个或多个最后一组.

This will only match sequences of one or more sequences of alphanumeric characters separated by a single -. If you do not want to allow single words (e.g. just hello), replace the * multiplier with + to allow only one or more repetitions of the last group.