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

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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