简体   繁体   中英

¿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. 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. 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. 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 . Or just be prepared to experiment a little.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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