【问题标题】:Regular expression X characters long, alphanumeric but not _ and periods, but not at beginning or end正则表达式 X 字符长,字母数字但不是 _ 和句点,但不在开头或结尾
【发布时间】:2013-05-09 18:58:37
【问题描述】:

正如主题所指出的,我需要一个 JavaScript 正则表达式 X 字符长,它接受字母数字字符,但不接受下划线字符,也接受句点,但不接受开头或结尾。句号也不能是连续的。

我几乎可以在 Stack Overflow (such as here) 上搜索和阅读其他人的问题和答案。

但是,在我的情况下,我需要一个字符串,该字符串的长度必须正好为 X 个字符(比如 6 个),并且可以包含字母和数字(不区分大小写),还可以包含句点。

所述句点不能连续,也不能开始或结束字符串。

Jd.1.4 有效,但Jdf1.4f 无效(7 个字符)。

/^(?:[a-z\d]+(?:\.(?!$))?)+$/i 

是我能够使用其他人的示例构建的,但我不能让它只接受与设定长度匹配的字符串。

/^((?:[a-z\d]+(?:\.(?!$))?)+){6}$/i

它现在可以接受不少于 6 个字符,但它也很乐意接受任何更长的字符...

我显然遗漏了一些东西,但我不知道它是什么。

谁能帮忙?

【问题讨论】:

  • 单独检查长度不是更容易吗(比如,foo.length == 6)?
  • 试试这个正则表达式:/^[a-z\d](?![^.]*[.]{2})[a-z\d.]{4}[a-z\d]$/i

标签: javascript regex


【解决方案1】:

这应该可行:

/^(?!.*?\.\.)[a-z\d][a-z\d.]{4}[a-z\d]$/i

解释:

^             // matches the beginning of the string
(?!.*?\.\.)   // negative lookahead, only matches if there are no
              // consecutive periods (.)
[a-z\d]       // matches a-z and any digit
[a-z\d.]{4}   // matches 4 consecutive characters or digits or periods
[a-z\d]       // matches a-z and any digit
$             // matches the end of the string

【讨论】:

  • 这接受 'j....f' 作为有效匹配。 See Fiddle。作者说“句号也不能连续。”
  • 嗯嗯……让我考虑一下。 edit: 混淆了lookhead 语法。已修复,现在应该可以使用了。
  • 这似乎可以解决问题。 现在有意义的事情之一。非常感谢!
【解决方案2】:

另一种方法:

/(?=.{6}$)^[a-z\d]+(?:\.[a-z\d]+)*$/i

解释:

      (?=.{6}$)   this lookahead impose the number of characters before 
                  the end of the string
      ^[a-z\d]+   1 or more alphanumeric characters at the beginning
                  of the string
(?:\.[a-z\d]+)*   0 or more groups containing a dot followed by 1 or 
                  more alphanumerics
              $   end of the string

【讨论】:

  • 基于几个测试,如果字符串类似于:J..14a,正则表达式会单独匹配 J
  • @Magro284:更正:我忘记了最后的 $
  • 我非常喜欢这个解决方案。干净,对我的思维方式有意义。
猜你喜欢
  • 2017-07-24
  • 2018-08-14
  • 2023-03-15
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多