正则表达式匹配以'-'分隔的字母数字单词 [英] Regex to match '-' delimited alphanumeric words

查看:69
本文介绍了正则表达式匹配以'-'分隔的字母数字单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试用户是否仅输入字母数字值或一个-".

I would like to test if user type only alphanumeric value or one "-".

hello-world                 -> Match
hello-first-world           -> match
this-is-my-super-world      -> match
hello--world                -> NO MATCH
hello-world-------this-is   -> NO MATCH
-hello-world                -> NO MATCH (leading dash)
hello-world-                -> NO MATCH (trailing dash)

到目前为止,这里是我所拥有的,但是我不知道如何实现-"符号来测试它(如果只有一次而不重复).

Here is what I have so far, but I dont know how to implement the "-" sign to test it if it is only once without repeating.

var regExp = /^[A-Za-z0-9-]+$/;

推荐答案

尝试一下:

/^[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.

这篇关于正则表达式匹配以'-'分隔的字母数字单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆