gpt4 book ai didi

java - 不包含两个或多个连续字符的正则表达式

转载 作者:行者123 更新时间:2023-12-02 08:20:25 27 4
gpt4 key购买 nike

我需要一个正则表达式,它匹配以字母开头和结尾且其间包含 4-8 个字符的字符串:A-z- _.

字符串不得包含两个或多个连续的 -._ 字符。

没有连续限制的正则表达式是 ^[A-z][A-z_\\.\\-]{4,8}[A-z]$ 如何在此处添加限制或者可能不可能?

我知道在正则表达式中对特定单词进行否定的首选方法是使用否定前瞻,但我不知道如何在这里实现它。

最佳答案

您可以预先使用否定前瞻来检查该字符类中是否没有任何连续字符。尝试使用这个正则表达式:

str.matches("(?!.*([._-])\\1)[A-Za-z][a-zA-Z._-]{4,8}[a-zA-Z]");

说明:

 (?!          // Start negative look-ahead (not followed by)
.* // Any string
( // Start capture group 1
[._-] // Any of ., _, -
)
\\1 // \1 (escaped \\1) Same character captured in capture group 1 (avoid consecutive)
) // Look-ahead ends
[A-Za-z] // Alphabets
[a-zA-Z._-] // Any of alphabets, ., -, _
{4,8} // repeated 4 to 8 times
[a-zA-Z] // ends with alphabet

关于java - 不包含两个或多个连续字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18902089/

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