gpt4 book ai didi

java - 在java正则表达式中结合白名单和黑名单

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:06:13 25 4
gpt4 key购买 nike

我在构建一个正则表达式时遇到问题,该正则表达式将允许除 2 个字符之外的所有 UTF-8 字符:'_' 和 '?'

所以白名单是:^[\u0000-\uFFFF]黑名单是:^[^_%]

我需要将这些组合成一个表达式。

我试过下面的代码,但没有按我希望的方式工作:

    String input = "this";
Pattern p = Pattern
.compile("^[\u0000-\uFFFF]+$ | ^[^_%]");
Matcher m = p.matcher(input);
boolean result = m.matches();
System.out.println(result);

输入:这个
实际输出:假
期望的输出:真

最佳答案

您可以使用 character class intersections/subtractions在 Java 正则表达式中限制“通用”字符类。

The character class [a-z&&[^aeiuo]] matches a single letter that is not a vowel. In other words: it matches a single consonant.

使用

"^[\u0000-\uFFFF&&[^_%]]+$"

匹配除_%以外的所有Unicode字符。

有关 Java 正则表达式中可用的字符类交集/减法的更多信息,请参阅 The Java™ Tutorials: Character Classes .

OCPSoft Visual Regex Tester 的测试将 % 添加到字符串时显示不匹配:

enter image description here

还有 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 - 在java正则表达式中结合白名单和黑名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36619048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com