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

正则表达式替换特定字符串中文件名处的单个字符

  •  1
  • kism3t  · 技术社区  · 8 年前

    我有以下场景:

    File '/oname=$INSTDIR\workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\SomeModule$SomeModulesData$SomeModulesDataBuilder.class'     '${ADDEDSOURCE}workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\SomeModule$SomeModulesData$SomeModulesDataBuilder.class'    ; Added file
    File '/oname=$INSTDIR\workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\CoolUtil.class'  '${ADDEDSOURCE}workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\CoolUtil.class'     ; Added file
    

    我想将名为*.class(也可以是其他的)的“$”符号替换为“$$”。我可以得到文件名,但只需要一组美元符号。

    下面是我的例子: https://regex101.com/r/Wa2cF6/2

    在java中,我只想做:

    public static void main(String[] args) {
    
        String s = "File '/oname=$INSTDIR\\workspace\\jetty\\work\\webapp\\WEB-INF\\classes\\com\\sample\\service\\core\\util\\SomeModule$SomeModulesData$SomeModulesDataBuilder.class' \t'${ADDEDSOURCE}workspace\\jetty\\work\\webapp\\WEB-INF\\classes\\com\\sample\\service\\core\\util\\SomeModule$SomeModulesData$SomeModulesDataBuilder.class' \t; Added file";
        s = s.replace("\\\\([a-zA-Z0-9_$]+)\\.\\w+'\\s", "$$");
        System.out.println(s);
    }
    

    并期望

    File '/oname=$INSTDIR\workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\SomeModule$$SomeModulesData$$SomeModulesDataBuilder.class'   '${ADDEDSOURCE}workspace\jetty\work\webapp\WEB-INF\classes\com\sample\service\core\util\SomeModule$$SomeModulesData$$SomeModulesDataBuilder.class'  ; Added file
    

    谢谢你的帮助。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Magyar Dávid    8 年前

    所以你想替换 $ 只在类名上签名?我肯定会使用索引和 StringBuilder 班级:

    private static final String testString =  "File '/oname=$INSTDIR\\workspace\\jetty\\work\\webapp\\WEB-INF\\classes\\com\\sample\\service\\core\\util\\SomeModule$SomeModulesData$SomeModulesDataBuilder.class' \t'${ADDEDSOURCE}workspace\\jetty\\work\\webapp\\WEB-INF\\classes\\com\\sample\\service\\core\\util\\SomeModule$SomeModulesData$SomeModulesDataBuilder.class' \t; Added file";
    
    public static void main(String[] args) {
        System.out.println(replaceDollars(testString));
    }
    
    private static final Pattern PATH = Pattern.compile("(\\'[\\S]*)(\\\\[\\w$]+\\.class\\')");
    
    public static String replaceDollars(String string) {
        Matcher m = PATH.matcher(string);
        StringBuilder builder = new StringBuilder();
        int end = 0;
    
        while (m.find()) {
            builder
                    .append(string, end, m.start())
                    .append(m.group(1))
                    .append(m.group(2).replace("$", "$$"));
            end = m.end();
        }
    
        builder.append(string, end, string.length());
    
        return builder.toString();
    }
    

    使用以下正则表达式: (\'[\S]*)(\\[\w$]+\.class\') 在输入字符串中查找文件。