gpt4 book ai didi

java - 正则表达式: exclusion in character class

转载 作者:行者123 更新时间:2023-12-02 03:35:37 25 4
gpt4 key购买 nike

我想匹配 a 和 z 之间的字母范围,x 除外。

我正在使用java.util.regex用于此目的的 API。

我的模式:

[a-z^x] // here a-z shows a range between a to z and ^ means negation 

示例

  • 如果我输入“a”,它应该匹配。
  • 如果我输入“x”,它应该不匹配

最佳答案

您可以按如下方式重写您的Pattern:

[a-z&&[^x]]

示例

String[] test = {"abcd", "abcdx"};
// | range
// | | and
// | | | new class excluding "x"
// | | | | adding quantifier for this example
Pattern p = Pattern.compile("[a-z&&[^x]]+");
for (String s: test) {
System.out.println(p.matcher(s).matches());
}

输出

true
false

关于java - 正则表达式: exclusion in character class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484739/

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