Andy
Andy

Reputation: 198

How to get everything between two words

This question is about regex.

I am currently using Node.js's child process's execFile. It returns a string, and I'm trying to get an array of names from the multi-lined string like below:

   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10

I've tried:

const regex_name = /pool: (.*)\b/gm;
let names = string.match(regex_name);
console.log(names); // returns [ 'name: Mike', 'name: Jake', 'name: Jack' ]

But what I want is:

['Mike', 'Jake', 'Jack']

What should I change in my regex?

Upvotes: 1

Views: 230

Answers (2)

Anthony
Anthony

Reputation: 6482

Can you just:

let names = string.match(regex_name).map(n => n.replace('name: ',''));

You could also use matchAll and extract the groups:

const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];

for(const match of matches) {
  results.push(match[1]);
}

Or functionally:

Array.from(string.matchAll(exp)).map(match => match[1]);

For older versions of node:

const exp = new RegExp('name:\\s(.+)','g');
const results = [];
let match = exp.exec(string);

while(match) {
  results.push(match[1]);
  match = exp.exec(string);
}

const string = `
   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10
`;

let names = string.match(/name:\s(.+)/g).map(n => n.replace('name: ',''));

console.log(names);

const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];

for(const match of matches) {
  results.push(match[1]);
}

console.log(results);

console.log(Array.from(string.matchAll(exp)).map(match => match[1]));

//Node 8 Update
const results2 = [];
let match = exp.exec(string);

while(match) {
  results2.push(match[1]);
  match = exp.exec(string);
}

console.log(results2);

Upvotes: 2

Nikhil
Nikhil

Reputation: 6641

You can use split() to get the text after name: and filter() to remove undefined values.

var str = `
   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10
   `;
   
const regex_name = /(.*)\b/gm;

let names = str.match(regex_name);

names = names.map(str => {
  if (str.includes("name")) {
    return str.split(':').pop().trim();
  }
}).filter(item => item);

console.log(names);

Upvotes: 1

Related Questions