【问题标题】:How to solve Unclosed character class error如何解决未闭合字符类错误
【发布时间】:2020-10-06 11:57:54
【问题描述】:

这是我的代码:

string.replaceAll("(?i)["+key+"]\\S*", "[blue]$0[blue]")

它抛出未封闭的字符类

【问题讨论】:

  • key 是否包含一些方括号?请记住,[] 在正则表达式中具有特殊含义,如果您希望它们代表实际的左右方括号,则需要对其进行转义。 Pattern.quote 可能会有所帮助。
  • String[] key = {"as","if","when","and","then"};
  • 您可能想要执行String r = "(?i)["+key+"]\\S*"; 并打印出r。这几乎肯定 不是 您想到的正则表达式。你想做什么?将[xxx](其中xxx 是这些词中的任何一个)替换为[blue]xxx[blue]?
  • 你最终想要的正则表达式是(?i)\b(as|if|when|and|then)\b ;没有涉及...+ key + ... 的字符串表达式会产生这种情况。
  • @KevinAnderson - String.join 如果我们可以相信密钥不包含正则表达式元字符,则应该可以解决问题。

标签: java regex string exception error-handling


【解决方案1】:

使用组,不要忘记避开你的替代方案:

import java.util.*;
import java.util.stream.*;
import java.util.regex.*;
 
class app
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> key = Arrays.asList("as","if","when","and","then");
        List<String> alternatives = key.stream()
            .map(Pattern::quote)
            .collect(Collectors.toList());
        String string = "AS?! When then";
        System.out.println( string.replaceAll("(?i)(?:"+String.join("|", alternatives)+")\\S*", "[blue]$0[blue]") );
    }
}

[**Java code demo**][1]

结果:[blue]AS?![blue] [blue]When[blue] [blue]then[blue]

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多