0

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.

asked Jan 25, 2015 at 19:04
1
  • 1
    Believe it or not, IntelliJ IDEA actually has a warning for your code, along with the suggestion how to fix it. Commented Jan 25, 2015 at 19:14

2 Answers 2

6

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.

answered Jan 25, 2015 at 19:05
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I knew it would be something simple like that, but I didn't know that a . was a regular expression in that method.
2

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).

answered Jan 25, 2015 at 19:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.