java - 如何使用正则表达式操作给定的字符串以获得两个不同的字符串?

标签 java regex string

我需要进行字符串操作。最初我将获得一个图像路径,如下所示:

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/

相关文章:

java - 如何在 Linux 和 Windows 上使用 JOGL 设置 IntelliJIdea 进行开发?

python - Python 正则表达式中的错误? (re.sub with re.MULTILINE)

string - 在Lua中修改字符串中的字符

Javascript 使用变量作为对象(数组)名称

regex - 捕获两个标记之间的文本

string - 从内存中的字符串加载 node.js 模块

java - 我怎样才能从它的大小找到大致的歌曲时间

java - eclipse中的堆和栈

java - 如何在java中给定单元格索引获取合并单元格的数据?

regex - 从字符串中删除 '$' 个字符