Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda