UserBulba
UserBulba

Reputation: 23

JavaScript Regex replacing multiple patterns

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!

Upvotes: 2

Views: 59

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

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);

Upvotes: 3

Barmar
Barmar

Reputation: 780688

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);

Upvotes: 2

Related Questions