正则表达式 - 不允许名称以连字符结尾 [英] regex - don't allow name to finish with hyphen

查看:47
本文介绍了正则表达式 - 不允许名称以连字符结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 javascript 创建一个正则表达式,它允许使用 abc-def 之类的名称但不允许 abc-(连字符也是唯一允许的非字母字符)

I'm trying to create a regex using javascript that will allow names like abc-def but will not allow abc- (hyphen is also the only non alpha character allowed)

名称必须至少为 2 个字符.我开始了^[a-zA-Z-]{2,}$但这还不够好所以我正在尝试这样的事情^([A-Za-z]{2,})+(-[A-Za-z]+)*$

The name has to be a minimum of 2 characters. I started with ^[a-zA-Z-]{2,}$ but it's not good enough so I'm trying something like this ^([A-Za-z]{2,})+(-[A-Za-z]+)*$

它可以有多个 - 在一个名称中,但不应以 - 开头或结尾 -

It can have more than one - in a name but it should never start or finish with -

它允许像 xx-x 这样的名字,但不允许像 x-x 这样的名字.我想实现 x-x 也被接受但不是 x-

It's allowing names like xx-x but not names like x-x. I'd like to achieve that x-x is also accepted but not x-

谢谢!

推荐答案

Option 1

此选项匹配以字母开头和结尾的字符串,并确保两个 - 不连续,因此像 a--a 这样的字符串无效.要允许这种情况,请参阅选项 2.

Option 1

This option matches strings that begin and end with a letter and ensures two - are not consecutive so a string like a--a is invalid. To allow this case, see the Option 2.

^[a-z]+(?:-?[a-z]+)+$

  • ^ 断言行首位置
  • [a-z]+ 匹配任何小写 ASCII 字母一次或多次(带有 i 标志,这也匹配大写变体)
  • (?:-?[a-z]+)+ 匹配以下一次或多次
    • -? 可选匹配 -
    • [a-z]+ 匹配任何 ASCII 字母(带有 i 标志)
      • ^ Assert position at the start of the line
      • [a-z]+ Match any lowercase ASCII letter one or more times (with i flag this also matches uppercase variants)
      • (?:-?[a-z]+)+ Match the following one or more times
        • -? Optionally match -
        • [a-z]+ Match any ASCII letter (with i flag)
        • var a = [
            "aa","a-a","a-a-a","aa-aa-aa","aa-a", // valid
            "aa-a-","a","a-","-a","a--a" // invalid
          ]
          var r = /^[a-z]+(?:-?[a-z]+)+$/i
          
          a.forEach(function(s) {
            console.log(`${s}: ${r.test(s)}`)
          })

          如果你想匹配像 a--a 这样的字符串,那么你可以使用下面的正则表达式:

          If you want to match strings like a--a then you can instead use the following regex:

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

          var a = [
            "aa","a-a","a-a-a","aa-aa-aa","aa-a","a--a", // valid
            "aa-a-","a","a-","-a" // invalid
          ]
          var r = /^[a-z]+[a-z-]*[a-z]+$/i
          
          a.forEach(function(s) {
            console.log(`${s}: ${r.test(s)}`)
          })

          这篇关于正则表达式 - 不允许名称以连字符结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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