gpt4 book ai didi

Java Regex - 使用别名更改路径

转载 作者:行者123 更新时间:2023-11-29 06:13:08 24 4
gpt4 key购买 nike

我有一个名为 $SERVER/public_html/ab1/ab2/的路径。

我想更改它,以便用我的用户目录代替 $SERVER。所以我愿意

path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir"));

但是当我运行它时,它会删除新字符串中的\。

F:Programming ProjectsJava Project/public_html/ab1/ab2/

最佳答案

Pattern有一个 String quote(String) 函数可以帮助您获取第一个字符串和 Matcher第二个有 String quoteReplacement(String):

path = path.replaceFirst(java.util.regex.Pattern.quote("$SERVER"), java.util.regex.Matcher.quoteReplacement(System.getProperty("user.dir")));

编辑:你必须转义任何东西的原因是因为第二个字符串的语义是 Matcher.appendReplacement它将反斜杠和美元视为转义下一个字符并插入捕获的组。

来自文档:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

一个更明显的解决方案是(小心需要用反斜杠转义)

 path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir").replaceAll("\\\\","\\\\\\\\"));

关于Java Regex - 使用别名更改路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6078504/

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