Question

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/";

Was it helpful?

Solution

Simply use replaceAll

BOSH_URL = BOSH_URL.replaceAll("(\\d+.){3}\\d+", "127.0.0.1");

OTHER TIPS

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

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top