Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace IP address from URI with another IP address using regex

Tags:

java

regex

String uri = "rtps://12.10.10.124/abc/12.10.22.10";

I'm trying to replace any first occurrence of IP address in this uri with let's say "127.0.0.1" using an efficient regex.
Taking into account that numbers with dots may be introduced in the uri at the end. The regex has to replace only the first occurrence of any IP-address in the URI.

Output would be:

uri = "rtps://127.0.0.1/abc/12.10.22.10";
like image 787
dropson Avatar asked Aug 25 '11 13:08

dropson


People also ask

What is the regex for IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

What is the general regular expression used for extracting IP address from logs?

The regular expression for valid IP addresses is : ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) \.){ 3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)


2 Answers

String ipRegex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
String uri2 = uri.replaceFirst(ipRegex, "127.0.0.1");

This of course matches any 4 groups of 1-3 digits separated by 3 dots (eg: 999.999.999.999 will match), if you want something that matches only legal IP addresses, you could go for:

String ipRegex = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

But I personally think this is overkill.

like image 140
NullUserException Avatar answered Oct 13 '22 12:10

NullUserException


s/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/127\.0\.0\.1/

transforms the first occurence of an ip address in a string to "127.0.0.1"

like image 40
Andreas Grapentin Avatar answered Oct 13 '22 11:10

Andreas Grapentin