முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 8 · பாடம் 3 இன் 4பாடத்திட்டத்தில் 31/32~12 min
தொகுதி பாடங்கள் (3/4)

URLகள் மற்றும் IPகளை பிரித்தெடுத்தல்

In free text (logs, articles, dumps) it's common to want to extract URLs and IP addresses. Let's look at robust patterns for both.

http/https URLs

Code
Pattern: https?:\/\/[\w.-]+(?:\:\d+)?(?:\/[^\s]*)?
  • https?:\/\/ -- scheme, with the s optional.
  • [\w.-]+ -- host (domain, subdomains, possibly localhost).
  • (?:\:\d+)? -- optional port.
  • (?:\/[^\s]*)? -- optional path, up to the first whitespace.

Captures https://example.com, http://localhost:3000/api/users, https://docs.dev/path?query=value.

IPv4

An IPv4 is 4 decimal octets separated by dots:

Code
Pattern: \b(?:\d{1,3}\.){3}\d{1,3}\b

"Good enough" version: it also accepts invalid values like 999.999.999.999. For the strict version you'd need range alternation (25[0-5]|2[0-4]\d|[01]?\d\d?), which is much longer.

Code
Pattern (strict): \b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b

Precision versus brevity

Matching URLs or IPs requires balancing pattern tolerance. A strict IP validator verifies that no octet exceeds 255. A practical extractor, on the other hand, typically looks for simplified patterns and delegates fine validation to dedicated code.

Try it

உடற்பயிற்சி#regex.m8.l3.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Find every http or https URL in the text. Scheme + host + optional path.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

https? for the optional s, [\\w.-]+ for the domain, and a group (?:\\/[^\\s]*)? for the optional path.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#regex.m8.l3.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Find every IPv4 (4 decimal octets separated by dots). Permissive version, no 0-255 check.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use (?:\\d{1,3}\\.){3} to repeat 'octet + dot' 3 times, then \\d{1,3} for the last one.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Additional challenge

உடற்பயிற்சி#regex.m8.l3.e3
முயற்சிகள்: 0ஏற்றுகிறது…

Find all IPv4 addresses in the format `X.X.X.X` (composed of four 1-to-3 digit numbers separated by dots).

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use \b to enforce boundaries, (?:\d{1,3}\.){3} to repeat the octet and dot three times, and finally \d{1,3}.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்