Reputation: 69
What is the regex to check where a string contains only 3 dots and digits like the following example:
let string =
"2.3.4.5
2.3.4.1
2.3.3.3"
where string can contain newline character ?
Upvotes: 3
Views: 2021
Reputation: 17170
Here is some logic you can sample in the direction of utility:
let str =
`2.3.4.5
2.44.2
2.3.4.1
234.622.166.2346
1.
127.0.0.1.
125.75.23.110
24.66.256.1
sie4wg4t7hweio478tedehyb5ryb
Thanks\r ok
\n\n
12.34.56.-8
2.3.3.3
3.4.2.4.5
poop
.34.5.34.
`
// beast mode function to check if string is a valid IP between 0-255
const isValidIP = (ip) => {
if (/^(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]?)$/.test(ip))
return true
return false
}
const results = str
.split('\n')
.reduce((all, ip) => {
const possibleIP = ip.match(/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/gm)
if (possibleIP && isValidIP(ip)) { all.valid.push(ip) }
else { all.invalid.push(ip) }
return all
}, { valid: [], invalid: [] })
console.log(results)
\n
to create an array of possible matchesreduce()
results.valid
results.invalid
results
objectUpvotes: 0
Reputation: 60354
A regex to match valid IPv4 addresses 0.0.0.0
-- 255.255.255.255
"\\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\b"
or, if each should occupy all of a single line:
"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
with setting that ^$
should match at linebreaks.
Upvotes: -1
Reputation: 702
This is where the regex .test()
operation makes sense.
/^(\d+\.\d+\.\d+\.\d+)+$/gm.test(str);
Upvotes: 1
Reputation: 24221
I think this might be what your after.
I've thrown in some invalid one's for good measure.
let str=
`2.3.4.5
2.44.2
2.3.4.1
2.3.3.3
3.4.2.4.5
`;
console.log(
str.match(/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/gm)
);
Upvotes: 3