Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Extract multiple strings from a long string efficiently in Javascript

I am trying to extract multiple strings using different patterns from one long string. I have done this successfully using different Regex queries but I feel this is not very efficient. Here is an example of the input string:

const input = ....Number of students: 5...[New]Break at 1:45 pm\nStudents involved are: John, Joseph, Maria\nLunch at 2:00 pm...Activities remaining: long jump, shuffle..

There are three prefixes which are used to extract the data after it:
const prefix1 = Students involved are:
const prefix2 = Activities remaining:
const prefix3 = Number of students:

The only pattern is a newline after each of the above three strings. Example: Students involved are: John, Joseph, Maria\n

I have used the following regex to accomplish this:

const students = input.match(new RegExp(prefix1 + "(.*)"));
const activities = input.match(new RegExp(prefix2 + "(.*)"));
const numOfStudents = input.match(new RegExp(prefix3 + "(.*)"));

Is there a better and more efficient way of accomplishing the above where I have to iterate through the long string only once?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can combine all the three regexs to one, like this: (?<=Number of students: )(?<number>[^\n]+).*?(?<=Students involved are: )(?<students>[^\n]+).*?(?<=Activities remaining: )(?<activities>[^\n]+)/gms

Then by using capture groups you can access all the three values that you want.

let s = `const input = ....Number of students: 5...
 at 1:45 pm
Students involved are: John, Joseph, Maria
Lunch at 2:00 pm...Activities remaining: long jump, shuffle..`

let pattern = /(?<=Number of students: )(?<number>[^\n]+).*?(?<=Students involved are: )(?<students>[^\n]+).*?(?<=Activities remaining: )(?<activities>[^\n]+)/gms

let m = pattern.exec(s)

console.log(m.groups.students)
console.log(m.groups.number)
console.log(m.groups.activities)

Since there is no pattern other than a newline after each of the mentioned lines, this will match anything till the newline, so you will need to clean up the matched values though.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda