我试图结合使用“not”和“or”来生成一组正则表达式匹配,如下所示:
"blah" matching "zero or more of" : "not h" or "any in b,l,a" = false
"blah" matching "zero or more of" : "any in b,l,a" or "not h" = false
"blah" matching "zero or more of" : "not n" or "any in b,l,a" = true
"blah" matching "zero or more of" : "any in b,l,a" or "not n" = true
我尝试了以下正则表达式,但它们似乎没有达到我想要的效果。我还包括了我对正则表达式的解释:
//first set attempt - turns out to be any of the characters within?
System.out.println("blah".matches("[bla|^h]*")); //true
System.out.println("blah".matches("[^h|bla]*")); //false
System.out.println("blah".matches("[bla|^n]*")); //false
System.out.println("blah".matches("[^n|bla]*")); //false
//second set attempt - turns out to be the literal text
System.out.println("blah".matches("(bla|^h)*")); //false
System.out.println("blah".matches("(^h|bla)*")); //false
System.out.println("blah".matches("(bla|^n)*")); //false
System.out.println("blah".matches("(^n|bla)*")); //false
//third set attempt - almost gives the right results, but it's still off somehow
System.out.println("blah".matches("[bla]|[^h]*")); //false
System.out.println("blah".matches("[^h]|[bla]*")); //false
System.out.println("blah".matches("[bla]|[^n]*")); //true
System.out.println("blah".matches("[^n]|[bla]*")); //false
所以,最后,我想知道以下问题:
- 我对上述正则表达式的解释是否正确?
- 符合我的规范的一组四个 Java 正则表达式是什么?
- (可选)我在正则表达式中是否犯了其他错误?
关于模糊需求,我想指出以下几点:
正则表达式分割可能类似于 ("not [abc]"或 "bc")* ,它将匹配任何类似 bcbc...
的字符串。或...
其中字符不是 a
s,b
s,或c
s。我只是选择“blah”作为一般示例,例如“foo”或“bar”。
最佳答案
“not h”可以有多种写法:
(?!.*h.*)
[^h]*
“b、l、a 中的任何一个”1:
[bla]*
1) 假设您的意思是“仅 b、l、a 之一”,否则问题中的所有 4 个示例都将为 true
使用或
组合将是:
[^h]*|[bla]*
表示“必须是不包含 h
的字符串,或者必须是仅包含 b
、l
和 的字符串>a
个字符。
在这种情况下,|
的顺序没有区别,因此 [^h]*|[bla]*
和 [bla]*| [^h]*
工作原理相同。
System.out.println("blah".matches("[bla]*|[^h]*")); //false
System.out.println("blah".matches("[^h]*|[bla]*")); //false
System.out.println("blah".matches("[bla]*|[^n]*")); //true
System.out.println("blah".matches("[^n]*|[bla]*")); //true
关于java - 在Java正则表达式中组合or和否定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57530164/