简体   繁体   English

slug的JS正则表达式字符串验证

[英]JS regex string validation for slug

I have an app, that allowing the end user to enter his desired slug. 我有一个应用程序,允许最终用户输入他想要的slug。 What I am looking for is a regex that check if the slug is valid. 我正在寻找的是一个正则表达式,检查slug是否有效。

In general, as valid a mean a string that start and ends with a latin leter, divided by dashes but not more than one dashes. 一般来说,有效的意思是指以拉丁语开头和结尾的字符串,除以破折号但不超过一个破折号。

More specific, the following is correct: 更具体地说,以下是正确的:

one-two-three

The following are not: 以下不是:

one---two-thee-
-one-two-three
one-two-three-

So with the following regex I am somewhow ok, but how can I check if in the middle of the string there are no more than two dashes ? 因此,使用以下正则表达式我可以,但是如何检查字符串中间是否有不超过两个破折号?

^[a-z][a-z][a-z]$

Is there a better way to write this regex, in order to meet my validation creteria ? 有没有更好的方法来编写这个正则表达式,以满足我的验证creteria?

http://regexpal.com/ can be a great webpage for checking your regexes as you write them. http://regexpal.com/可以是一个很好的网页,可以在您编写时检查您的正则表达式。 A handy tool :). 一个方便的工具:)。

Having a look at yours, should it accept capital letters/numbers? 看看你的,它应该接受大写字母/数字吗? If so maybe this will help : 如果是这样,也许将帮助:

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

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 (eg just hello), replace the * multiplier with + to allow only one or more repetitions of the last group. 如果您不想允许单个单词(例如,只是hello),请将*乘数替换为+,以仅允许最后一个组的一次或多次重复。

Here's a link to a live sample from the same thread to demonstrate. 这是从同一个线程中演示的实时样本的链接。

Changing around the A-Za-z0-9 inside the squares will allow you to only accept capitals,non-capitals or numbers as is appropriate to you. 在方块内围绕A-Za-z0-9进行更改将允许您仅接受适合您的大写字母,非大写字母或数字。

Good luck and let me know if you have any more questions ! 祝你好运,如果你有任何疑问,请告诉我! :) :)

^[a-z][a-z\-]*[a-z]$

actually this should be your regex and your validation should be tested in two phases. 实际上这应该是你的正则表达式,你的验证应分两个阶段进行测试。

The first one by this regex, which will be a basic test, the second one can be done by splitting on hiphens and checking again the same regex on the splitted strings. 这个正则表达式的第一个是基本测试,第二个可以通过拆分hipns并再次检查分割字符串上的相同正则表达式来完成。

My personal favourite : 我最喜欢的:

^[a-z](-?[a-z])*$

Begin with a lowercase letter; 以小写字母开头; then more lower or maybe a hyphen, but not without another lower right after it. 然后更低或可能是连字符,但不是没有另一个右下方。

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

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