Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegEx for Consecutive Expressions with OR?

How can i match a series of expressions with OR’s? This is for scrubbing plain text data which may contain imbedded spaces or tabs at the front of each row. This is in preparation for a .split at newlines.

const oldStr = `abc
   abc
    abc`;

I want to replace:

newline + 0 or more spaces OR tabs 

with

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newline

This achieves what i want

newStr = oldStr.replaceAll(/\n */g, "\n");  // newline + spaces
newStr = newStr.replaceAll(/\n\t*/g, "\n");  // newline + tabs

How to do that in a single statement? The following fail:

Attempt, with pipe:

newStr = oldStr.replaceAll(/\n *|\t*/g, "\n");

Attempt, with parens around the OR:

newStr = oldStr.replaceAll(/\n( *|\t*)/g, "\n");

Attempt, with slashes around the OR:

newStr = oldStr.replaceAll(/\n/ *|\t*/g, "\n");

Attempt, with square brackets instead of pipe:

newStr = oldStr.replaceAll(/\n[ *\t*]/g, "\n");

Attempt, with quotes and pipe:

newStr = oldStr.replaceAll("\n *\t|*/g", "\n");

Attempt, with quotes and pipe and parens:

newStr = oldStr.replaceAll("\n( *|\t*)/g, "\n");

Attempt, with quotes and square brackets:

newStr = oldStr.replaceAll("\n[ *\t*]/g", "\n");

Feel free to offer a solution which combines the cleaning with a .split statement, or a non-regex solution.

>Solution :

You don’t need to "prepare" for splitting, just split by \n, optionally surrounded by spaces:

text = `   How razorback-jumping 
   frogs 
can
 \t   level six \t
         \t piqued gymnasts!`         
         
console.log(text.trim().split(/[ \t]*\n[ \t]*/g))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading