200-201 Question 314
Single answerYou are tasked with filtering log entries to identify IP addresses from a server log file. The log contains entries such as 'User logged in from 192.168.1.100' and 'Connection received from 10.0.0.5'. Which regular expression would you use to match valid IPv4 addresses?
- A
\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b
- B
\b\d{1,2}.\d{1,2}.\d{1,2}.\d{1,2}\b
- C
\b\d{3}.\d{3}.\d{3}.\d{3}\b
- D
\b[0-9]+.[0-9]+.[0-9]+.[0-9]+\b
Show answer and explanation
Correct answer: A
Explanation
The correct regular expression '\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b' properly matches IPv4 addresses by ensuring that each segment consists of 1-3 digits and is separated by dots. The use of word boundaries ensures that only complete IP addresses are matched, avoiding partial matches in larger strings.
- A. Correct.
This is the correct regular expression for matching IPv4 addresses. It accounts for numbers between 1 and 3 digits separated by dots and is bounded by word boundaries to prevent partial matches.
- B. Incorrect.
This regex incorrectly limits the segments of the IP address to a maximum of 2 digits, which would exclude valid IP addresses like '192.168.1.100'.
- C. Incorrect.
This regex incorrectly requires all segments of the IP address to have exactly 3 digits, which would exclude valid IP addresses like '10.0.0.5'.
- D. Incorrect.
Although this regex matches numbers separated by dots, it is not bounded by word boundaries, which may lead to partial matches or unintended results in complex text.