gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:51:08 25 4
gpt4 key购买 nike

我是正则表达式的新手,似乎无法为我需要做的事情做正确的语法。我需要一个字母数字字符串的正则表达式,该字符串可以是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com