Reputation: 168
I have a html textarea in which im expecting users to input either a mac address or an ip on each line, as many as they want. Is there a way to match the whole text including the new lines as a single match and if any of the lines dont comply fail?
Example of expected formats per line on any line:
192.168.0.0
10.0.0.0
0.0.0.0
255.255.255.255
000000000000
0000.0000.0000
00:00:00:00:00:00
00-00-00-00-00-00
Experimenting and mixing 2 different regex for macs and for ips i got this far, which matches each individual case: https://regex101.com/r/tQ0fuk/1 I haven't worked with multi-line regex before so im cannot say i fully understand them and this question could be rubbish lol
Im aware i could do line by line processing and fail if any line fails or skip that line, but i got curios to how far can this be pushed with regex.
Any experts :)
Upvotes: 0
Views: 202
Reputation: 15268
Rearranged IP check so triple digits are matched first (prevent incomplete line matching which would cause failed checks). Assuming that the IP and MAC matches are accurate.
Removed multiline and global and used whitespace|endofstring check in place of end of line check.
Used full string matching.
const ipOrMac = str => /^(((([0-9A-Fa-f]{12})|(([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4}))|(((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])))(\s|$))+$/.test(str);
console.log(ipOrMac(
`192.168.0.0
10.0.0.0
0.0.0.0
255.255.255.255
000000000000
0000.0000.0000
00:00:00:00:00:00
00-00-00-00-00-00
aaa`));
console.log(ipOrMac(
`192.168.0.0
10.0.0.0
0.0.0.0
255.255.255.255
000000000000
0000.0000.0000
00:00:00:00:00:00
00-00-00-00-00-00
`));
Upvotes: 1