Home > Back-end >  How can I obtain the text out of this string using a regex?
How can I obtain the text out of this string using a regex?

Time:10-08

I can't found a solution after try and retry to regex this string

const regexp = /[!\\](.*?)[!\\]/g;
const str = '\t\t\t\t\t\t\tPareri del comitato tecnico-consultivo - legge 488/92  (1996-2013)\t\t\t\t\t\t'  
    '\n\t\t\t\t\t\t\tContratto di Sviluppo (precedente alla riforma 2014)\t\t\t\t\t\t';
    
const array = [...str.matchAll(regexp)];
console.log(array); // Outputs `[]`

//const title = array[1];
//console.dir(array[4][1])

I expect to retrieve only: "Pareri del comitato tecnico-consultivo - legge 488/92 (1996-2013)" but i'm not able to find a solution :(

CodePudding user response:

Maybe this is helpful to you?

const regexp = /[\t]*([^\t] )[\t]*\n*/g;
const str = '\t\t\t\t\t\t\tPareri del comitato tecnico-consultivo - legge 488/92  (1996-2013)\t\t\t\t\t\t'  
    '\n\t\t\t\t\t\t\tContratto di Sviluppo (precedente alla riforma 2014)\t\t\t\t\t\t';
    
const array = [...str.matchAll(regexp)].map(r=>r[1]);
console.log(array); // Outputs `[]`

CodePudding user response:

I think you just need to split the string into an array of lines with \n and then .trim each line to remove any leading and trailing whitespace.

A regex is not necessary in this case.

const str = '\t\t\t\t\t\t\tPareri del comitato tecnico-consultivo - legge 488/92  (1996-2013)\t\t\t\t\t\t'  
    '\n\t\t\t\t\t\t\tContratto di Sviluppo (precedente alla riforma 2014)\t\t\t\t\t\t';
    
const array = str.split('\n').map(line => line.trim());
console.log(array);

Full credit: This is pretty much exactly Wiktor Stribiżew's answer.

  • Related