简体   繁体   English

如何从 java 中生成的字符串中删除所有转义字符,并且 java string replace() 不适用于 `\\`

[英]How to remove all escape characters from a string generated in java ,and java string replace() not working for `\`

I have the following method in my Java Spring MVC web application that will store a Freemarker Template in a Java String .我在我的Java Spring MVC web 应用程序中有以下方法,它将在Java String存储一个Freemarker Template

private String processTemplate(Map<String, Object> variablesMap, String templateData)
    {
        Template template  = null;
        Writer out = new StringWriter();
        try 
        {
            template = new Template("userCollection", new StringReader(templateData), new Configuration());
            template.process(variablesMap, out);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (TemplateException e) 
        {
            e.printStackTrace();
        }
        return out.toString();
    }

The String that is generated would be something like the following:生成的字符串类似于以下内容:

\r\n</li>\r\n<li class=\"col-md-4 col-sm-6\">\r\n<div class=\"feature-box\">\r\n<div class=\"user-details\">\r\n<h4 class=\"shorter\">\r\nDeveloper\r\n</h4>\r\n<p class=\"tall\">\r\nName : <strong>Leo Ralph</strong><br/>\r\nFamily Name : <strong>An quo impetus percipit efficiantur</strong><br/>\r\nNickname : <strong>An quo impetus percipit efficiantur</strong><br/>\r\n</p>\r\n</div>\r\n</div>\r\n</li>

And what I actually require is:而我真正需要的是:

<li class="col-md-4 col-sm-6">
<div class="feature-box">
<div class="user-details">
<h4 class="shorter">
Developer
</h4>
<p class="tall">
Name : <strong>Leo Ralph</strong><br/>
Family Name : <strong>An quo impetus percipit efficiantur</strong><br/>
Nickname : <strong>An quo impetus percipit efficiantur</strong><br/>
</p>
</div>
</div>
</li>

Is there any way that I can do this in java.有什么办法可以在java中做到这一点。

As per the suggestions from the comments, I have tried the following:根据评论中的建议,我尝试了以下方法:

collectionData = collectionData.replace("\r", "");
collectionData = collectionData.replace("\t", "");
collectionData = collectionData.replace("\n", "");
collectionData = collectionData.replace("\\", "");

But the \\ is still there.但是\\仍然存在。 The other characters have gone now.其他角色现在已经消失了。

You could use the replace() method from String class.您可以使用 String 类中的replace()方法。

/* This will actually be stored as "Line 1\\r\\nLine 2\\r\\nLine 3" */
String example = "Line 1\\r\\nLine 2\\r\\nLine 3";
example = example.replace("\\r\\n", "\n");
System.out.println(example);

The following code will print out:将打印出以下代码:

Line 1
Line 2
Line 3

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

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