[英]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 {' ]
我有结果:
[ '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
.我有结果:
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);
例如,如果结尾在新行的开头,并且下一行应该是
use(456, Ttt);
on it's own:在其自己的:
^[^\S\n]*class Ttt {[^]*?\n\s*}\s*\n\s*use\(.*\);$
Note that \s
can also match newlines.请注意,
\s
也可以匹配换行符。
The pattern in parts:部分图案:
^
Start of string ^
字符串开头[^\S\n]*
Match optional whitespace chars without newlines [^\S\n]*
匹配不带换行符的可选空白字符class Ttt {
Match literally class Ttt {
字面匹配[^]*?
Match any character including newlines, as few as possible\n\s*}\s*
Match a newline and }
between optional whitespace chars \n\s*}\s*
匹配可选空白字符之间的换行符和}
\nuse\(.*\);
Match a newline and use(...);
use(...);
$
End of string $
字符串结尾 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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.