简体   繁体   English

Java正则表达式负向前瞻不能正常工作

[英]Java regex negative lookahead not working properly

I'm having a struggle creating a regex that verifies if a string does not end in a sequence of X characters (the same one). 我正在努力创建一个正则表达式来验证字符串是否以X字符序列(同一个字符)结尾。

For example: x=5 例如:x = 5

1xxxxx - should fail
1xxx - should pass

My regex so far : 1(?!\\\\w\\1{4}) does not work. 到目前为止我的正则表达式: 1(?!\\\\w\\1{4})不起作用。 Returns false in both cases. 两种情况都返回false。

Thanks 谢谢

您需要添加字符串锚点结束:

1(?!.*(.)\1{4,}$).*$

This was a tough one, but if the condition in your question is correct, "string does not end in a sequence of X characters", this should do it: 这是一个艰难的,但如果你的问题中的条件是正确的,“字符串不以X字符序列结束”,这应该这样做:

(?:(.)(?:(?:(?!\1).){1,4})|^(.)\2{0,3})$

It's basically two possible alterations inside a non-capturing group (?: - ) . 它基本上是非捕获组内的两种可能的改变(?: - )

The last part - ^(.)\\2{0,3} - simply tests if its a complete string consisting of only one character, less than five long. 最后一部分 - ^(.)\\2{0,3} - 只测试它是否只包含一个字符,小于五个字符的完整字符串。

The first part - (.)(?:(?:(?!\\1).){1,4}) - checks for a change of character by capturing one, and by a negative look-ahead making sure it doesn't match the next one, which is matched by the . 第一部分 - (.)(?:(?:(?!\\1).){1,4}) - 通过捕获一个来检查角色的变化,并通过负面的预测来确定它没有t匹配下一个匹配的. and tested for a repetition of less than four times 并测试重复次数少于四次

The both alterations is tested for end of string $ outside the group. 两个变更都在组外的字符串$结尾进行测试。

Check it out here at regex101 . 请在regex101查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM