Home > Mobile >  Cut multiline string with RegEx and javascript
Cut multiline string with RegEx and javascript

Time:02-04

I have example text:

var text = `class Eee {
   test(){
     console.log("123");
   }
}
use(123, Eee);

class Ttt {
   test(){
     console.log("123");
   }
}
use(456, Ttt);


class Ooo {
   test(){
     console.log("123");
   }
}
use(111, Ooo);
`;

And I wont get part text for example:

`class Ttt {
   test(){
     console.log("123");
   }
}
use(456, Ttt);`

If I use RegEx:

let result = text.match(/^class Ttt \{(.*)/gm); 

I have result: [ 'class ttt {' ]

If I use RegEx:

let result = text.match(/^class Ttt \{(.*)\}/gm); 

or

let result = text.match(/^class Ttt \{(.*)use\([\b].Ttt\);/gm);

I have result: null. How can I get the entire piece of text I want, not the first line?

CodePudding user response:

You specified where the match should start, but you also have to specify where is should end.

If the end for example is at the start of a new line and the next line should be use(456, Ttt); on it's own:

^[^\S\n]*class Ttt {[^]*?\n\s*}\s*\n\s*use\(.*\);$

Note that \s can also match newlines.

The pattern in parts:

  • ^ Start of string
  • [^\S\n]* Match optional whitespace chars without newlines
  • class Ttt { Match literally
  • [^]*? Match any character including newlines, as few as possible
  • \n\s*}\s* Match a newline and } between optional whitespace chars
  • \nuse\(.*\); Match a newline and use(...);
  • $ End of string

Regex demo

var text = `class Eee {
   test(){
     console.log("123");
   }
}
use(123, Eee);

class Ttt {
   test(){
     console.log("123");
   }
}
use(456, Ttt);


class Ooo {
   test(){
     console.log("123");
   }
}
use(111, Ooo);
`;

const regex = /^[^\S\n]*class Ttt {[^]*?\n\s*}\s*\n\s*use\(.*\);$/m;
const m = text.match(regex);

if (m) {
  console.log(m[0]);
}

CodePudding user response:

For what it's worth, here's a non-regex version:

'class '   text.split('class ')[1]

var text = `class Eee {
   test(){
     console.log("123");
   }
}
use(123, Eee);

class Ttt {
   test(){
     console.log("123");
   }
}
use(456, Ttt);


class Ooo {
   test(){
     console.log("123");
   }
}
use(111, Ooo);
`;

console.log('class '   text.split('class ')[1])

  •  Tags:  
  • Related