sss
sss

Reputation: 69

How to check if the string contains only dots and numbers

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

Answers (4)

agm1984
agm1984

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)
  1. split by \n to create an array of possible matches
  2. run each match through an accumulator, reduce()
  3. if IP is valid, add it to results.valid
  4. if IP is anything else, add it to results.invalid
  5. investigate results object

Upvotes: 0

Ron Rosenfeld
Ron Rosenfeld

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

Sam R
Sam R

Reputation: 702

This is where the regex .test() operation makes sense.

/^(\d+\.\d+\.\d+\.\d+)+$/gm.test(str);

Upvotes: 1

Keith
Keith

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

Related Questions