Luiz Alves
Luiz Alves

Reputation: 2645

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:

I have tried:

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

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

Upvotes: 3

Views: 42

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

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"));

Upvotes: 4

Related Questions