Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IP value from textarea with regular expression

Here is a textarea.(IPv4, Domain)

96.17.109.65 fox.com

And I want to change IP value into another one. like this,

74.125.71.106 fox.com

I guess it will be like

$('textarea').find('some regular expressions..').val('another one...');

Please help me. I just wanna learn regular expressions.. thanks.

like image 519
Deckard Avatar asked May 20 '11 08:05

Deckard


People also ask

How do you represent an IP address in regex?

\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.

How to validate IP address in JavaScript?

To check if a string is a valid IP address (IPv4) in JavaScript, we can use a regex expression to match for the allowed number range in each of the four decimal address sections.

What is IP address pattern?

An IP address consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (e.g., 0.0. 0.0 to 255.255. 255.255).


Video Answer


1 Answers

Matching an IP address using regular expression is not as easy as it sounds. There are two methods available:

simple, but can lead to false-positives:

\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b

complex, but always correct:

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

If you want to replace it, you'll need something like this (using the simple RegExp as an example):

var textarea = $('textarea');
textarea.val(textarea.val().replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, '74.125.71.106'));
like image 112
jwueller Avatar answered Nov 09 '22 13:11

jwueller