java 白名单,在java正则表达式中组合白名单和黑名单

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:

F94nI.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值