简体   繁体   English

¿可以用*,$,%替换所有吗? 如果没有 ¿

[英]¿Can replaceAll work with *,$,%? if no ¿What other alternative to replaceAll can i use?

So, im trying to make this code where if i detect one of this symbols (* ! OX % $ # + &), then that specific symbol will be eliminated from the string.所以,我试图制作这个代码,如果我检测到这个符号之一(*!OX%$#+&),那么那个特定的符号将从字符串中删除。 However, im getting this error message但是,我收到此错误消息

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*

I asumme is due to the function replaceAll not being able to recognize these char.我认为是由于函数 replaceAll 无法识别这些字符。 If so, can someone tell me please another way to do what im trying to do.如果是这样,有人可以告诉我另一种方式来做我想做的事情。

(I have to verify if each char is on a certain String separetly, one by one) (我必须逐个验证每个字符是否在某个字符串上)

Yes, replaceAll can work with any of those characters, but the argument to replaceAll is a regular expression.是的, replaceAll可以处理这些字符中的任何一个,但是replaceAll的参数是一个正则表达式。 That means that characters that have a special meaning in a regular expression need to be "escaped" by preceding them with a backslash.这意味着在正则表达式中具有特殊含义的字符需要通过在它们前面加上反斜杠来“转义”。 Then, of course, that backslash needs to be escaped from the compiler by preceding it with a second backslash.然后,当然,反斜杠需要通过在它前面加上第二个反斜杠来从编译器中转义。 So you'll end up writing things like所以你最终会写出这样的东西

replacedString = myString.replaceAll("\\+", "PLUS");

To find out which characters need to be replaced, look at the Javadoc for the Pattern class .要找出需要替换的字符,请查看Pattern 类Javadoc Or just be prepared to experiment a little.或者只是准备好尝试一下。

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

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