簡體   English   中英

使用 RegEx 和 javascript 剪切多行字符串

[英]Cut multiline string with RegEx and javascript

我有示例文本:

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);
`;

而且我不會得到部分文本,例如:

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

如果我使用正則表達式:

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

我有結果: [ 'class ttt {' ]

如果我使用正則表達式:

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

或者

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

我有結果: null 我怎樣才能得到我想要的整段文字,而不是第一行?

您指定了比賽應該從哪里開始,但您還必須指定應該在哪里結束。

例如,如果結尾在新行的開頭,並且下一行應該是use(456, Ttt); 在其自己的:

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

請注意\s也可以匹配換行符。

部分圖案:

  • ^字符串開頭
  • [^\S\n]*匹配不帶換行符的可選空白字符
  • class Ttt {字面匹配
  • [^]*? 盡可能少地匹配任何字符,包括換行符
  • \n\s*}\s*匹配可選空白字符之間的換行符和}
  • \nuse\(.*\); 匹配換行符並use(...);
  • $字符串結尾

正則表達式演示

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

對於它的價值,這是一個非正則表達式版本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM