2

I need to modify the regex, which does the following for me.

Changes the IP list, the list can be longer or shorter.

1.1.1.1,2.2.2.2

to a string such as:

[{"{#ADDR}":"1.1.1.1"},{"{#ADDR}":" 2.2.2.2"}]

in the following line:

return '{$PING_LIST}'.replace(/([^,]+)/g,'{"{#ADDR}":"$1"}').replace(/(.*)/,'[$1]')

But I need to add the hostname to the list as well.

1.1.1.1-NODE1,2.2.2.2-NODE2

and get something like this

[{"{#ADDR}":"1.1.1.1","{#NODE}":"NODE1"},{"{#ADDR}":"2.2.2.2","{#NODE}":"NODE2"}]

I tried to get the hostname, this way:

(?<=-)(\w+)(?=,)

but I can't figure out the correct syntax and combine it with the previous expression.

Very grateful for any help!

0

2 Answers 2

3

Your desired result string looks like a Javascript array with objects. If that is the case, you can use 2 capture groups:

\b((?:\d{1,3}\.){3}\d{1,3})-(\w+)

See a regex demo for the capture group values.

const s = "1.1.1.1-NODE1,2.2.2.2-NODE2";
const regex = /\b((?:\d{1,3}\.){3}\d{1,3})-(\w+)/g;
const m = Array.from(s.matchAll(regex), m => {
  return {
    "{#ADDR}": m[1],
    "{#NODE}": m[2]
  }
})
console.log(m);

Sign up to request clarification or add additional context in comments.

Comments

2

Use ((?:\d+\.){3}\d+) to match the IP.

let pinglist = '1.1.1.1-NODE1,2.2.2.2-NODE2';
let result = pinglist.replace(/((?:\d+\.){3}\d+)-([^,]+)/g, '{"{#ADDR}":"$1","{#NODE}":"$2"}')
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.