简体   繁体   English

通过String方法删除或替换“|”字符

[英]Remove or Replace “|” character by String method

I would like to remove character "|" 我想删除字符“|” by using String#replaceAll() method. 通过使用String#replaceAll()方法。 But first parameter is recognized regex meta character. 但第一个参数是识别正则表达式元字符。

I tried replaceAll("\\|", ""); 我试过replaceAll("\\|", ""); with escape character, but it cannot be compiled. 具有转义字符,但无法编译。

Are there any way to remove or replace "|" 有没有办法删除或替换“|” character by Java? Java的角色?

You need to double-escape the | 你需要双重逃避| when using replaceAll() , like: 当使用replaceAll() ,如:

myString.replaceAll("\\|", "");

This is because your string actually gets parsed twice , first as a literal string and then as a regular expression. 这是因为你的字符串实际上被解析了两次 ,首先是文字字符串,然后是正则表达式。 So when you start with "\\\\|" 所以当你以"\\\\|"开头 the first parse gives you a literal string of \\| 第一个解析为你提供了一个文字字符串\\| , which the regex parser then recognizes as | ,正则表达式解析器然后识别为| . This can be a bit confusing until you get used to it. 在你习惯它之前,这可能有点令人困惑。

The correct answer is, don't use replaceAll() (which replaces regexes), use replace() which simply replaces a character: 正确的答案是,不要使用replaceAll() (替换正则表达式),使用replace()简单地替换一个字符:

replace("|", "");

fyi, despite the method name not having "all" in it, is does in fact replace all instances of the specified character. fyi,尽管方法名称中没有“all”,但实际上确实替换了指定字符的所有实例。

Also, this does the job too: 此外,这也完成了这项工作:

String test = "Hello | Hi | Test";
System.out.println(test.replace("|", ""));

String replace method is a useful tool here. 字符串替换方法是一个有用的工具。 No need to use regexes. 无需使用正则表达式。

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

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