简体   繁体   English

ReplaceAll替换除我指定的内容以外的所有内容

[英]ReplaceAll replacing everything but what I specify

I wish to replace all instances of a pipe in a specific string with something else. 我希望用其他东西替换特定字符串中管道的所有实例。 However, not only is it not replacing the specified string but instead replacing all blank spaces. 但是,它不仅不会替换指定的字符串,而且还会替换所有空格。 Example: 例:

String cleanTitle = StringEscapeUtils.escapeHtml("Bacon is | good");
out.println(cleanTitle.replaceAll("|", "*"))

This example is outputting *B*a*c*o*n*i*s*|*g*o*o*d* 此示例输出* B * a * c * o * n * i * s * | * g * o * o * d *

I need it to say Bacon is * good 我需要说培根很好

-The function escapeHTML is necessary for my interface, despite this example not using it for my question. -尽管本示例未将其用于我的问题,但函数escapeHTML是我的界面所必需的。

The String#replaceAll() does a regex matching and replacement. String#replaceAll()进行正则表达式匹配和替换。 The | | is a special character in regex and therefore needs to be escaped with \\ as answered by Jasper. 是正则表达式中的特殊字符,因此需要用\\转义,如Jasper所回答。 However, you actually wanted a simple char-by-char search and replacement. 但是,您实际上想要一个简单的逐字符搜索和替换。 The String#replaceAll() is the wrong tool for the purpose. 为此, String#replaceAll()是错误的工具。 You should be using String#replace() instead. 您应该使用String#replace()代替。

out.println(cleanTitle.replace('|', '*'));

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

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