简体   繁体   English

JS正则表达式-允许使用双连字符

[英]JS Regex - allow double hyphen

I have the below regex to do some validation for user input. 我使用下面的正则表达式对用户输入进行一些验证。

^\s{0}$|^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?)*\.?$

The user input will be in the format myInvoices--2015Jan12--04-10-11 用户输入的格式为myInvoices--2015Jan12--04-10-11

However, the regex above only allows names with 1 hyphen/dash: myInvoices-2015Jan12-04-10-11 rather than double dashes. 但是,上面的正则表达式仅允许使用带有1个连字符/破折号的名称:myInvoices-2015Jan12-04-10-11而不是双破折号。

Can someone tell me how can I allow the user to input double dashes as well? 有人可以告诉我如何允许用户输入双破折号吗?

Thanks 谢谢

^\s{0}$|^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-{1,2}){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-{1,2}){0,61}[0-9A-Za-z])?)*\.?$

我为您添加了{1,2} -允许一两个破折号

You should just need to add -? 您只需要添加-? , ie an optional hyphen, after each current hyphen. ,即每个当前连字符后的可选连字符。 So \\b- becomes \\b--? 所以\\b-变成\\b--? :

^\s{0}$|^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b--?){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b--?){0,61}[0-9A-Za-z])?)*\.?$

This matches your sample input 这与您的样本输入匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM