我需要进行字符串操作。最初我将获得一个图像路径,如下所示:
image = images/registration/student.gif
image = images/registration/student_selected.gif
image = images/registration/student_highlighted.gif
我需要操作字符串图像路径来获取 2 个不同的图像路径。
一种是获取路径:
image1 = images/registration/student.gif
为此我使用了以下函数:
private String getImage1(final String image) {
String image1 = image;
image1 = image.replace("_highlight", "");
image1 = image.replace("_selected", "");
return image1;
}
我需要的第二个图像路径是获取路径:
image2 = image = images/registration/student_selected.gif
我用来获取image2
输出的函数是:
private String getImage2(final String image) {
String image2 = image;
boolean hasUndersore = image2.matches("_");
if (hasUndersore) {
image2 = image2.replace("highlight", "selected");
} else {
String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
return image2;
}
但是上述方法并没有给我预期的结果。有人可以帮我吗? 非常感谢!
最佳答案
你可以使用indexOf(...)而不是match()。 match 将根据正则表达式检查整个字符串。
for (final String image : new String[] { "images/registration/student.gif", "images/registration/student_highlight.gif",
"images/registration/student_selected.gif" }) {
String image2 = image;
final boolean hasUndersore = image2.indexOf("_") > 0;
if (hasUndersore) {
image2 = image2.replaceAll("_highlight(\\.[^\\.]+)$", "_selected$1");
} else {
final String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
System.out.println(image2);
}
这将为您提供预期的输出。
顺便说一句,我更改了replaceAll(..) 正则表达式,因为图像文件名也可以包含字符串“highlight”。例如stuhighlight_highlight.jpg
关于java - 如何使用正则表达式操作给定的字符串以获得两个不同的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225331/