Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove lines with a specific char with javascript and regex

I have some text files containing something as:

CID Principal CID 2 CID 3 CID 4
-
-
-
-
Observações Gerais:
Paciente relata dor cronica ,agudizada e limitante do joelho direito , edema +/3+, nega trauma ou queda, dor a palpação na interlinha articular medial.
Hipótese Diagnóstica:
Conduta:
Lisador dip, restiva 5 mg adesivos, gelo, fisioterapia, Rx da bacia, joelhos com carga e orientações.

I´d like a regex to get rid of:

  • all empty lines
  • lines containing only "-" and no more chars.

I have tried:

mytext.replace(/^\s*[\r\n\-]/gm, "");

But no luck. How could I do that using javascript?

like image 514
Luiz Alves Avatar asked Sep 06 '26 12:09

Luiz Alves


1 Answers

If the lines with hyphens always consist of a single hyphen, you might as well go with a non-regex solution like

text.split("\n").filter(x => x.trim().length > 0 && x != '-').join("\n")

As for a regex solution, you can use

/^(?:\s*|-+)$[\r\n]*/gm

See the regex demo. Note it will remove lines that consist of one or more hyphens, if this is not expected replace -+ with -.

Details:

  • ^ - start of a line
  • (?:\s*|-+) - either zero or more whitespaces or one or more hyphens
  • $ - end of line
  • [\r\n]* - zero or more CR or LF chars.

See a JavaScript demo:

const text = "CID Principal CID 2 CID 3 CID 4\n-\n-\n-\n-\nObservações Gerais:\nPaciente relata dor cronica ,agudizada e limitante do joelho direito , edema +/3+, nega trauma ou queda, dor a palpação na interlinha articular medial.\nHipótese Diagnóstica:\nConduta:\nLisador dip, restiva 5 mg adesivos, gelo, fisioterapia, Rx da bacia, joelhos com carga e orientações.";
const regex = /^(?:\s*|-+)$[\r\n]*/gm;
console.log(text.replace(regex, ''));
// Non-regex solution:
console.log(text.split("\n").filter(x => x.trim().length > 0 && x != '-').join("\n"));
like image 53
Wiktor Stribiżew Avatar answered Sep 08 '26 01:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!