Negative Lookaround Regex - 仅出现一次 - Java [英] Negative Lookaround Regex - Only one occurrence - Java
问题描述
我正在尝试查找一个字符串是否包含仅一个出现的单词,
I am trying to find if a string contains only one occurrence of a word ,
例如
String : `jjdhfoobarfoo` , Regex : `foo` --> false
String : `wewwfobarfoo` , Regex : `foo` --> true
String : `jjfffoobarfo` , Regex : `foo` --> true
多个 foo
可能出现在字符串的任何位置,因此它们可以不连续,
multiple foo
's may happen anywhere in the string , so they can be non-consecutive,
我用字符串 foobarfoo
在 java 中测试了以下正则表达式匹配,但它不起作用,它返回 true :
I test the following regex matching in java with string foobarfoo
, but it doesn't work and it returns true :
static boolean testRegEx(String str){
return str.matches(".*(foo)(?!.*foo).*");
}
我知道这个主题可能看起来重复,但我很惊讶,因为当我使用这个正则表达式时:(foo)(?!.*foo).*
它有效!
I know this topic may seem duplicate , but I am surprised because when I use this regex : (foo)(?!.*foo).*
it works !
知道为什么会这样吗?
推荐答案
使用两个锚定前瞻:
static boolean testRegEx(String str){
return str.matches("^(?=.*foo)(?!.*foo.*foo.*$).*");
}
几个关键点是,有一个负面的前瞻来检查 2 个锚定开始的 foo,重要的是包含输入的结尾.
A couple of key points are that there is a negative look-ahead to check for 2 foo's that is anchored to start, and importantly containes an end of input.
这篇关于Negative Lookaround Regex - 仅出现一次 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!