代码之家  ›  专栏  ›  技术社区  ›  Dan

正则表达式导致模式语法异常

  •  0
  • Dan  · 技术社区  · 5 年前

    我正在尝试创建一个#replaceAll regex来归档某些字符。

    我试了以下方法

    msg.replaceAll("[^\\w~!@#$%^&*()-=_+`[]{}\\|:;'\"<>,./\\]", "");
    

    但它给了我这个错误

    INFO Caused by: java.util.regex.PatternSyntaxException: Unclosed character class near index 36
    07.09 00:07:24 [Server] INFO [^\w~!@#$%^&*()-=_+`[]{}\|:;'"<>,./\]
    07.09 00:07:24 [Server] INFO ^
    

    0 回复  |  直到 5 年前
        1
  •  1
  •   flyingfox    5 年前

    对于regex表达式,您需要添加 \\ 最后一次之前 ] [ ,你也需要逃跑 - ,将其更改为

    [^\w~!@#$%^&*()\-=_+`\[\]{}\|:;'\"<>,./]
    

    在我这边很管用

    msg = msg.replaceAll("[^\\w~!@#$%^&*()\\-=_+`\\[\\]{}\\|:;'\\\"<>,./]", "");
    
        2
  •  1
  •   Emma    5 年前

    我的猜测是,也许这个表达可能是需要的或接近的:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    public class re{
    
        public static void main(String[] args){
    
    
            final String regex = "[^\\w~!@#$%^&*()=_+`\\[\\]{}|:;'\"<>,.\\\/-]";
            final String string = "ábécédééefg";
            final String subst = "";
    
            final Pattern pattern = Pattern.compile(regex);
            final Matcher matcher = pattern.matcher(string);
    
            final String result = matcher.replaceAll(subst);
    
            System.out.println(result);
    
        }
    }
    

    输出

    bcdefg
    

    如果你想探索/简化/修改这个表达式,它是 regex101.com . 如果你愿意,你可以 也可以在 this link ,如何匹配 对照一些样本输入。