简体   繁体   中英

Cut multiline string with RegEx and javascript

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?

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]); }

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM