在java正则表达式中组合白名单和黑名单 [英] Combine whitelist and blacklist in java regex expression
问题描述
我在构建正则表达式时遇到问题,该正则表达式允许使用除2个字符外的所有UTF-8字符:'_'和'?'
所以白名单是:^ [\\\000000-\\\ 00FFFF]
,黑名单是:^ [^ _%]
我需要将这些结合起来一个表达式。
我尝试了以下代码,但是没有按照我希望的方式工作:
String input =this;
模式p =模式
.compile(^ [\\\ -\\\FFFF] + $ | ^ [^ _%]);
Matcher m = p.matcher(输入);
boolean result = m.matches();
System.out.println(result);
输入:这个
实际输出:false
期望输出:true
您可以使用
和 Java演示:
字符串输入=这个;
模式p = Pattern.compile([\\\000000-\ uFFFF&& [^ _%]] +); //没有锚点,因为使用`matches()`
Matcher m = p.matcher(输入);
boolean result = m.matches();
System.out.println(result); // => true
I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: '_' and '?'
So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]
I need to combine these into one expression.
I have tried the following code, but does not work the way I had hoped:
String input = "this";
Pattern p = Pattern
.compile("^[\u0000-\uFFFF]+$ | ^[^_%]");
Matcher m = p.matcher(input);
boolean result = m.matches();
System.out.println(result);
input: this
actual output: false
desired output: true
You can use character class intersections/subtractions in Java regex to restrict a "generic" character class.
The character class
[a-z&&[^aeiuo]]
matches a single letter that is not a vowel. In other words: it matches a single consonant.
Use
"^[\u0000-\uFFFF&&[^_%]]+$"
to match all the Unicode characters except _
and %
.
More about character class intersections/subtractions available in Java regex, see The Java™ Tutorials: Character Classes.
A test at the OCPSoft Visual Regex Tester showing there is no match when a %
is added to the string:
And the Java demo:
String input = "this";
Pattern p = Pattern.compile("[\u0000-\uFFFF&&[^_%]]+"); // No anchors because `matches()` is used
Matcher m = p.matcher(input);
boolean result = m.matches();
System.out.println(result); // => true
这篇关于在java正则表达式中组合白名单和黑名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!