zoukankan      html  css  js  c++  java
  • java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

    使用repalceAll 方法出现java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0异常

    代码如下:

    1     @Test
    2     public void testReplaceAll(){
    3         String sql = "select * from per_handle where id not in('3ce7405509414105a65e7456987e7393')";        
    4          String countSql = sql.replaceAll("*", " count(*) ");
    5 
    6         System.out.println(countSql);
    7     }    

    以junit测试方式运行后报了如下错误:

      java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

    出现这个错误与repalceAll方法有关,查阅java API文档可以看到 replaceAll方法结构如下:

    String java.lang.String.replaceAll(String regex, String replacement) 

    使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。

    第一个参数是一个正则表达式,第二个参数为替换后的字符串。

    由于"*"在正则表达式中有特殊意义,导致报错。

    尝试了两种解决方法:

    1、对"*"进行转义处理,使之成为一个普通字符

    1 @Test
    2 public void testReplaceAll(){
    3     String sql = "select * from per_handle where id not in('3ce7405509414105a65e7456987e7393')";        
    4     String countSql = sql.replaceAll("\*", " count(*) ");
    5     System.out.println(countSql);
    6 }

    2、使用replace方法代替replaceAll方法

    1 @Test
    2 public void testReplaceAll(){
    3     String sql = "select * from per_handle where id not in('3ce7405509414105a65e7456987e7393')";        
    4     String countSql = sql.replace("*", " count(*) ");
    5     System.out.println(countSql);
    6 }

    这种方法能够成功的原因是:

    String java.lang.String.replace(CharSequence target, CharSequence replacement)

    replace方法的第一参数为字符或字符串,所以默认会将"*"当成普通字符串。

  • 相关阅读:
    Windows 下安装 Python环境安装
    关于form表单提交ajaxForm和ajaxSubmit的用法与区别
    .NET Core Runtime 和 .NET Core SDK
    路由表中没有与提供的值匹配的路由
    SQL server Cannot find one or more
    CentOS7安装完毕,重新开机启动后显示: Initial setup of CentOS Linux 7 (core)
    private static
    接口和抽象类
    static const readonly
    frameset的使用小结
  • 原文地址:https://www.cnblogs.com/zuidongfeng/p/5582269.html
Copyright © 2011-2022 走看看