Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!