繁体   English   中英

尝试使用正则表达式解析和替换Java模式

[英]Trying to parse and replace pattern in Java using regex

我已经尝试解决了近3天的问题。 而且我仍然不知道如何解决。
有一个输入字符串(例如):

In software, a stack overflow [apple] occurs when too much memory [orange] is used on the call stack [banana]. 
The call stack [pear] contains a limited amount of memory, often determined at the start of the program [apple].

我想做的是将[apple][orange][banana][pear]一词替换为<img src="apple.jpg"><img src="orange.jpg"><img src="banana.jpg"><img src="pear.jpg">
实际上,经过将近1天的时间,我发现了一个正则表达式,可以找到以"["开头和以"]"结尾的模式,即(?<=\\\\[)\\\\w+(?=])
我不知道如何存储单词列表([apple],[orange] ...)。
我应该使用HashMap还是ArrayList
以及如何在HashMapArrayList循环以在“最快时间内”替换为对应的字符串?

在此示例中,列表仅包含4个内容。 但实际上,列表中可能有500多个东西。
尽管我找到了模式,但仍然无法解决此问题,因为我不知道如何在输入字符串中找到所有模式,然后找出所有模式,然后检查列表中是否存在此模式,然后替换用正确的字符串。
请注意,在此示例中, [apple]被替换为<img src="apple.jpg"> ,但实际上[ xxx ]中的xxx .jpg可能不同。 但我有此映射的列表。
我真的很想解决这个问题,请帮助我解决并提供示例代码。
非常感谢你。

String poem = "In software, a stack overflow [apple] occurs"
    + " when too much memory [orange] is used on the call stack [banana]."
    + " The call stack [pear] contains a limited amount of memory,"
    + " often determined at the start of the program [apple].";

Map<String, String> rep = new HashMap<String, String>();

rep.put("[apple]", "<img src='apple.jpg' />");
rep.put("[banana]", "<img src='banana.jpg' />");
rep.put("[orange]", "<img src='orange.jpg' />");
rep.put("[pear]", "<img src='pear.jpg' />");

for (Map.Entry<String, String> entry : rep.entrySet()) {
    poem = poem.replace(entry.getKey(), entry.getValue());
}

// poem now = what you want.

如果您坚持使用正则表达式执行此任务...

String poem = "In software, a stack overflow [apple] occurs"
                + " when too much memory [orange] is used on the call stack [banana]."
                + " The call stack [pear] contains a limited amount of memory,"
                + " often determined at the start of the program [apple].";

        List<String> fruits = new ArrayList<String>();
        fruits.add("[apple]");
        fruits.add("[banana]");
        fruits.add("[pear]");
        fruits.add("[orange]");

        String pattern = "\\[(?<=\\[)(\\w+)(?=])\\]";
        poem = poem.replaceAll(pattern, "<img src='$1.jpg' />");

        System.out.println(poem);

您可以看到代码的动态运行

我对regex还是很陌生,但是我相信您想要做的是使用分组以及模式和匹配器来替换匹配的特定部分。

您想对正则表达式进行分组,并仅用相关代码替换“ [”和“]”。

String poem = "In software, a stack overflow [apple] occurs when too much memory    [orange] is used on the call stack [banana]. The call stack [pear] contains a limited amount   of memory, often determined at the start of the program [apple].";
Pattern p = Pattern.compile("(\\[)(\\w*)(\\])");
Matcher m = p.matcher(poem);
poem = m.replaceAll("<img src='$2.jpg' />");

这就是我为使它适用于您的示例所做的。 希望能有所帮助(它至少帮助我学习了正则表达式!)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM