I am trying to get the IP address of an incoming connection and then store it in a YML file (the SnakeYML API). I have receiving the IP down pat, and I tested with a incoming local connection that correctly returned "127.0.0.1".
However, when I run this method on it:
address.replaceAll(".", "-");
The return is this: "---------" (I have to replace the periods because SnakYML uses periods as path separators)
It's probably something really stupid, but I can't figure it out.
-
1Believe it or not, IntelliJ IDEA actually has a warning for your code, along with the suggestion how to fix it.Marko Topolnik– Marko Topolnik2015年01月25日 19:14:23 +00:00Commented Jan 25, 2015 at 19:14
2 Answers 2
You need to use "\\." instead of ".". The reason is that . is a regular expression that matches any character. So you need to escape it to make it match only an actual dot - write address.replaceAll("\\.", "-");.
An alternative would be to use the replace method in place of replaceAll, which interprets its arguments literally, instead of as regular expressions. So address.replace(".", "-"); will do what you want.
1 Comment
replaceAll uses regex and in regex . represents any character (except line separators) so you need to escape ., for instance via "\\." or "[.]" (one element character class).
But clearer and probably faster way would be using replace(char, char) like
address = address.replace('.', '-');
which doesn't use regex engine.
You can also use replace(CharSequence target, CharSequence replacement) which will automatically escape all regex metacharacter from both arguments (yes, replacement can also have some special characters which can be used by regex engine).