我是正则表达式的新手。基本上,我想匹配" private"的所有实例,但仅当它们出现在构造函数的参数列表中时。
以下是我的示例文字:
constructor(
private optionsService: OptionsService,
private modalService: BsModalService,
private renderer: Renderer2,
private messageService: MessageService,
private queryBuilderService: QueryBuilderService,
private ltPlacementService: LtPlacementService,
private sanitizer: DomSanitizer
) { } // All of the above should match
private someOtherVariable; // Should not match
有没有办法匹配构造函数(...){}中的所有内容,然后匹配" private"的实例。只有在这个结果?提前谢谢。
答案 0 :(得分:1)
要从constructor(
匹配到) {
,您可以使用constructor\(([\s\S]+(?=\)\s*{))
,然后在捕获组(组1)中捕获其间的文本。
那将匹配
constructor
按字面意思匹配\(
匹配((
捕获小组(第1组)
[\s\S]+
匹配任何空白或非空白字符(?=
确定后续内容的积极前瞻
\)\s*{
匹配),零个或多个空格和{)
关闭积极前瞻)
关闭捕获组然后从第1组中的文字匹配private
:
例如:
let string = `constructor(
private optionsService: OptionsService,
private modalService: BsModalService,
private renderer: Renderer2,
private messageService: MessageService,
private queryBuilderService: QueryBuilderService,
private ltPlacementService: LtPlacementService,
private sanitizer: DomSanitizer
) { } // All of the above should match
private someOtherVariable; // Should not match`;
const pattern = /constructor\(([\s\S]+(?=\)\s*{))/g;
pattern.exec(string)[1].match(/\bprivate\b/g).forEach((p) => {
console.log(p);
});