java - 在Java正则表达式中组合or和否定?

标签 java regex string-matching regex-negation

我试图结合使用“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

所以,最后,我想知道以下问题:

  1. 我对上述正则表达式的解释是否正确?
  2. 符合我的规范的一组四个 Java 正则表达式是什么?
  3. (可选)我在正则表达式中是否犯了其他错误?

关于模糊需求,我想指出以下几点:
正则表达式分割可能类似于 ("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 的字符串,或者必须是仅包含 bl 的字符串>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/

相关文章:

java - Spring 3.1, hibernate 4,SessionFactory

java - ThreadLocal 和 SimpleDateFormat 数组

java - 验证搜索 arrayList

java - 删除字符串数组中的重复字符串

java - 日历返回错误的当前日期android

python - 在 Python 中写一个正则表达式来获取一个子串

asp.net - asp :RegularExpressionValidator with format MMddyy (leap year issue) 的正则表达式

javascript - RegExp 未捕获类型错误 : Cannot read property '1' of null

algorithm - 一次搜索多个模式的最佳字符串匹配算法是什么?

与一或零不匹配的字符串模式匹配