我有以下情况:
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替换* .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
感谢您的帮助。
答案 0 :(得分:0)
因此,您只想在类名中替换$
符号吗?我肯定会使用索引和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\')
在输入字符串中查找文件。