Home > Software engineering >  Regex string split with multiple conditions
Regex string split with multiple conditions

Time:02-11

(Javascript older version of Node.js)

Edit I have to clear up what I want.

I have multiple lines like these

var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;

My desired outputs are

name1

name2

nam

nam

n1

So I am trying codes like this.

/[^;]*/

But I need help because I have multiple patterns. Some may have semicolons/space/null after the variable names, I need to omit those.

CodePudding user response:

use /(?<=(var\s )|(let\s )|(const\s ))(\w )/gim

let data = `
var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;
`;
data = data.match(/(?<=(var\s )|(let\s )|(const\s ))(\w )/gim);
console.log(data); // [ 'name1', 'name2', 'nam', 'nam', 'n1' ]

CodePudding user response:

Use regexp = /name[1-9] /g

let arr = ['var person;', 'CONST    name2', '   Let  nam;', '  VAr n1  ;'];
var result = [];
for(var s of arr) {
    var split_array = s.replace(/   /g, ' ').trim().split(' ');
    result.push(split_array[1].replace(';', ''))
}
console.log(result);

  • Related