How to Replace only Ip in the below string in file with java file operation
var BOSH_URL = "http://192.168.50.107:7070/http-bind/";

- 856
- 1
- 7
- 18
4 Answers
You will first need to read the files content. Then you could use a regular expression that matches the ip address (e.g. \d+\.\d+\.\d+\.\d+
) and replace it with the new one. When you've done that write it back in the file again.
Here is a regex tester: http://www.regexplanet.com/advanced/java/index.html
Here a tutorial of how to read and write files: http://www.java-samples.com/showtutorial.php?tutorialid=392

- 2,846
- 4
- 22
- 51
-
I used `newline=line.replaceAll("//.*:", "new IP");` for replace but not worked properly. – Dinesh Dabhi Dec 20 '13 at 10:03
-
take a look at the regex tester to find out the regex that fits your needs. FYI `//.*` matches everthing after `http:`. So `"http://192.168.50.107:7070/http-bind/"` will become `http:newIP` – mvieghofer Dec 20 '13 at 10:05
Simply use replaceAll
BOSH_URL = BOSH_URL.replaceAll("(\\d+.){3}\\d+", "127.0.0.1");

- 25,147
- 6
- 59
- 55
-
Maybe replaceFirst is better suitable. Otherwise maybe parts of the URL can be replaced, too (not only the ip address). – mvieghofer Dec 20 '13 at 10:08
As Shoaib Chikate said you can use string concatenation, and I suggest you to use StringBuilder like in var BOSH_URL = new StringBuilder("http://").append(ipAddress).append(port).append("/http-bind")
If you chose java regex to replace the IP, you must be very carefully with that; some example posted have flaws. For instance: "(\\d+.){3}\\d+"
can also match '999.999.999.99999999' which is not a valid IP. Therefore, additional logic is required to check for validity (if that is needed in your case).
OR
Change the BOSH_URL as var BOSH_URL = "http://@ipAddress:@port/http-bind/"
and after getting the real IP and port you cand do BOSH_URL.replace("@ipAddress", realIPAddress).replace("@port", realPort);
To just replace one ip don't write big logic containing replaceFirst replace blah blah blah Instead declared variable for that and change that variable.
var ipAddress=null
var BOSH_URL="http://"+ipAddress+":7070/anyAdress"

- 8,665
- 12
- 47
- 70