regex - 字符串中单次出现的正则表达式

标签 regex

我是正则表达式的新手,似乎无法为我需要做的事情做正确的语法。我需要一个字母数字字符串的正则表达式,该字符串可以是 1-8 个字符长并且最多可以包含 1 个破折号,但不能单独是一个破折号。

有效:

A-
-A
1234-678
ABC76-

无效:

-
F-1-
ABCD1234-
---   

提前致谢!

最佳答案

一种方式。 (很抱歉,如果这已经发布了)

 #  ^(?=[a-zA-Z0-9-]{1,8}$)(?=[^-]*-?[^-]*$)(?!-$).*$

 ^                              # BOL
 (?= [a-zA-Z0-9-]{1,8} $ )      # 1 - 8 alpha-num or dash
 (?= [^-]* -? [^-]* $ )         # at most 1 dash
 (?! - $ )                      # not just a dash
 .* $

编辑:只需将其扩展为以逗号分隔的段

 #  ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,)),?[^,]*)+(?<!,)$


 ^                         # BOL
 (?! , )                   # does not start with comma
 (?:                       # Grouping
      (?=
           (?: ^ | , )
           [a-zA-Z0-9-]{1,8}         # 1 - 8 alpha-num or dash
           (?: $ | , )
      )
      (?=
           (?: ^ | , )
           [^-]* -? [^-]*            # at most 1 dash
           (?: $ | , )
      )
      (?!
           (?: ^ | , )
           -                         # not just a dash
           (?: $ | , )
      )
      ,? [^,]*                  # consume the segment
 )+                        # Grouping, do many times

 (?<! , )                  # does not end with comma
 $                         # EOL

Edit2:如果你的引擎不支持lookbehinds,这是一样的,但没有

 #  ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,))(?!,$),?[^,]*)+$


 ^                         # BOL
 (?! , )                   # does not start with comma
 (?:                       # Grouping
      (?=
           (?: ^ | , )
           [a-zA-Z0-9-]{1,8}         # 1 - 8 alpha-num or dash
           (?: $ | , )
      )
      (?=
           (?: ^ | , )
           [^-]* -? [^-]*            # at most 1 dash
           (?: $ | , )
      )
      (?!
           (?: ^ | , )
           -                         # not just a dash
           (?: $ | , )
      )
      (?! , $ )                 # does not end with comma

      ,? [^,]*                  # consume the segment
 )+                        # End Grouping, do many times

 $                         # EOL

关于regex - 字符串中单次出现的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059637/

相关文章:

java - Java 7 中的正则表达式命名捕获组支持

javascript - 意外的 JavaScript 行为问题

php - 如何解决 €25.99 vs 25.99€ preg_match 问题?

python正则表达式匹配并替换字符串的开头和结尾但保留中间

regex - 正则表达式长度 (0) 或 (7-50)

html - 没有适用于 'xpathApply' 的方法应用于类 "NULL"的对象

javascript - Node.js:获取 "From: "和 "To: "的正则表达式

regex - 从文件名中删除某些字符串模式而不影响扩展名

regex - 检查 URL 协议(protocol)的正则表达式

php - 将逗号(,)替换为点(.)RegEx php