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

188
Visualizações
Select specific Text between two strings (multiline)

I want to Select specific text between two strings using regex.

e.g:

foo I have four toys bar    //single line

foo     //multiline
I
have
four
toys
bar

foo I have three pets bar

foo
I
have
three
pets bar

How to select text between "foo" and "bar" with specific word containing "four"

Output:

I have four toys

I
have
four
toys

My code:

foo[\s\S]*?(four)[\s\S]*?bar

My code is working fine but problem is that when when "four" word does not comes between "foo" and "bar" it is selecting all text till "four" word

foo I have three pets bar

foo I have four toys bar

foo
I
have
three
pets bar

I just want text between "foo" and "bar" when it is containg specific word "four"

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

0

We can use the following regex pattern, in dot all mode:

\bfoo\s+(?:(?!\bbar\b).)*?\s+four\s+(?:(?!\bfoo\b).)*?\s+bar

var input = `foo I have four toys bar

foo
I
have
four
toys
bar

foo I have three pets bar

foo
I
have
three
pets bar`;

var matches = input.match(/\bfoo\s+(?:(?!\bbar\b).)*?\s+four\s+(?:(?!\bfoo\b).)*?\s+bar/gs)
                   .map(x => x.replace(/^foo\s+|\s+bar$/g, ""));
console.log(matches);

An explanation to this complex regex pattern might be helpful here:

\bfoo\s+            match 'foo' followed by one or more whitespace characters
(?:(?!\bbar\b).)*?  match any content WITHOUT encountering 'bar'
\s+four\s+          match 'four' surrounded by whitespace
(?:(?!\bfoo\b).)*?  match any content WITHOUT encountering 'foo'
\s+bar              whitespace followed by ending 'bar'

Note that due to the way match() behaves, we also have a map step where we strip off leading foo and ending bar from every match.

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