【发布时间】:2019-12-23 02:30:44
【问题描述】:
我正在尝试结合使用“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... 或 ... 的字符串,其中字符不是 as、bs、或cs。我只是选择“blah”作为一般示例,例如“foo”或“bar”。
【问题讨论】:
-
这不是负前瞻,因为那是在避免未来的元素。我只想检查当前元素是否匹配。
-
@Turing85 它是否定的,但是在
[]的字符集上下文中 -
仅供参考:
[^h|bla]表示“不是h、|、b、l或 @987654334 @",但^只在首位有特殊含义,所以[bla|^h]表示“一个b,l,a,|,^,或者h”。跨度> -
@Andreas 哦,这听起来有问题。以后我会记住这一点的:)
-
总体评论:您当前的正则表达式语义说:如果一个字符既不是
'b'、'l'或'a',那么它一定不是'h'。换句话说:一个字符可以是任何东西,除了h。这真的是你想要的吗?
标签: java regex string-matching regex-negation