Как получить все между двумя словами - PullRequest
1 голос
/ 18 октября 2019

Этот вопрос о regex.

В настоящее время я использую дочерний процесс Node.js execFile. Он возвращает строку, и я пытаюсь получить массив имен из многострочной строки, как показано ниже:

   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10

Я пробовал:

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

Но чтоЯ хочу это:

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

Что я должен изменить в моем regex?

Ответы [ 2 ]

2 голосов
/ 18 октября 2019

Можете ли вы просто:

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

Вы также можете использовать matchAll и извлечь группы:

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

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

Или функционально:

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

Длястарые версии узла:

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);
1 голос
/ 18 октября 2019

Вы можете использовать split () для получения текста после name: и filter () для удаления undefined значений.

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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...