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

195
Vistas
use regex to replace spaces that occur with a value depending on how many spaces found

I want to use a regex that looks for spaces with a minimum length of 2 in a row, and replaces the occurrence with another value for each occurrence of the space found.

For example:

I love   to eat    cake

There are 3 spaces after love and 4 spaces after eat. I want my regex to replace occurrences of a space more than 1, and to replace it with a value for each occurrence found.

The output I am trying to go for:

I love---to eat----cake

I tried something like

myStr.replace(/ +{2,}/g, '-')
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You may use this code with a lookahead and a lookbehind:

const s = 'I love   to eat    cake'

var r = s.replace(/ (?= )|(?<= ) /g, '-');

console.log(r);
//=> 'I love---to eat----cake'

RegEx Details:

  • (?= ): Match a space only if that is followed by a space
  • |: OR
  • (?<= ) : Match a space only if that is preceded by a space
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can match two or more whitespaces and replace with the same amount of hyphens:

const s = 'I love   to eat    cake'
console.log(s.replace(/\s{2,}/g, (x) => '-'.repeat(x.length)) )

The same approach can be used in Python (since you asked), re.sub(r'\s{2,}', lambda x: '-' * len(x.group()), s), see the Python demo.

Also, you may replace any whitespace that is followed with a whitespace char or is preceded with whitespace using

const s = 'I love   to eat    cake'
console.log(s.replace(/\s(?=\s|(?<=\s.))/gs, '-') )
console.log(s.replace(/\s(?=\s|(?<=\s\s))/g, '-') )

See this regex demo. Here, s flag makes . match any char. g makes the regex replace all occurrences. Also,

  • \s - matches any whitespace
  • (?=\s|(?<=\s.)) - a positive lookahead that matches a location that is immediately followed with a whitespace char (\s), or (|) if it is immediately preceded with a whitespace and any one char (which is the matched whitespace). If you use (?<=\s\s) version, there is no need of s flag, \s\s just makes sure the whitespace before the matched whitespace is checked.
about 4 years ago · Juan Pablo Isaza 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