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

155
Vistas
How can I improve my regex string and replacement string to get what I need as output?

I want using regex to detect all the new line character (\n) that are put by users by mistake. For example

# abcd abcd abcd abcd 
efgh efgh efgh efgh       

   ## ijk ijk ijk ijk ijk ijk 
lmn lmn lmn    

 # opq opq opq opq       
rst rst rest  rst 
 

To be corrected to following

# abcd abcd abcd abcd efgh efgh efgh efgh 
## ijk ijk ijk ijk ijk ijk lmn lmn lmn 
#opq opq opq opq rst rst rest  rst 

I am trying to use this regex string :

\s*\n+[\s]*[^#]+

to be replaced by "" (blank string)

ie. Find a \n character that

  1. May or may not have multiple spaces before it.
  2. Can be followed by multiple spaces
  3. But the space following \n should not have a # after it. Eg. \n # . Because # should always start a new line, and if # too is included and replaced by "" it will start appearing on the same line as previous one.

The answer after replacement with \n is this, which is not desired:

 # abcd abcd abcd abcdfgh efgh efgh efgh## ijk ijk ijk ijk ijk ijkmn lmn lmn# opq opq opq opqst rst rest  rst 

How can I improve my regex string and replacement string to get what I need as output?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You may use this regex:

(?:\s*\n)+\s*(?!\s*#)|^\s+|[ \t]*$

RegEx Demo

Code:

const s = `# abcd abcd abcd abcd 
efgh efgh efgh efgh       

   ## ijk ijk ijk ijk ijk ijk 
lmn lmn lmn    

 # opq opq opq opq       
rst rst rest  rst
`;

var r = s.replace(/(?:\s*\n)+\s*(?!\s*#)|^\s+|[ \t]*$/mg, '');

console.log(r);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You may try with that:

^[ \t]*([#]+[^\n]+)\n[ \t]*([^#\n]+.*?)\n

and replace by this:

$1$2

Demo

const regex = /^[ \t]*([#]+[^\n]*?)[ \t]*\n[ \t]*([^#\n]+.*?)\n/gm;
const str = `# abcd abcd abcd abcd 
efgh efgh efgh efgh       

   ## ijk ijk ijk ijk ijk ijk 
lmn lmn lmn    

 # opq opq opq opq       
rst rst #rest  rst 
`;
const subst = `$1$2`;
const result = str.replace(regex, subst);
console.log(result);

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