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

时间:2013-05-01 14:13:12

标签: java 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。jpg在[xxx]中可能不同。但是我有一个这个映射列表 我真的想解决这个问题,请帮我解决并提供样本编码 非常感谢你。

3 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

如果你坚持使用正则表达式完成这项任务......

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);

您可以看到代码的this dynamic run

答案 2 :(得分:0)

我仍然是正则表达式的新手,但我相信你想要做的是使用分组和模式和匹配器来替换匹配的特定部分。

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

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' />");

这就是我为了你的例子而努力的方法。希望有所帮助(它帮助我至少学习正则表达式!)。