简体   繁体   English

Javascript正则表达式:找到第一个'use strict'

[英]Javascript regex: find the first 'use strict'

I'd like to determine whether the file begins with zero or more single-line comments (the // style), followed by "use strict". 我想确定文件是以零或多行单行注释(//样式)开头,然后是“use strict”。

Here's my attempt: 这是我的尝试:

var regex = new RegExp("(\/\/.*$)*\"use strict\";", 'm');
var codeblock = 
`
//hi
//there
"use strict";
`;

let match = regex.exec(codeblock);
console.log(match.index);

I'd expect match.index to be 0. However, it actually returns 14, meaning it doesn't recognize my comments. 我希望match.index为0.然而,它实际上返回14,这意味着它不能识别我的评论。 I suspect I didn't use the repeating pattern ()* correctly, but I'm not sure what I should be using? 我怀疑我没有正确使用重复模式()*,但我不确定我应该使用什么?

The point is that your (\\/\\/.*\\r?\\n)* part does not match the comments since you are not consuming the linebreaks, you only assert their presence with $ . 关键是您的(\\/\\/.*\\r?\\n)*部分与评论不匹配,因为您没有使用换行符,只能用$断言它们的存在。 Thus, Group 0 value is undefined (try printing match[1] ) and the match is found at Position 14, ie "use strict" . 因此,组0值未定义 (尝试打印match[1] )并且匹配位于位置14,即"use strict"

Replace $ with \\r?\\n and make sure you have no newline at the start of the test string, and you will get 0 : $替换$ \\r?\\n并确保在测试字符串的开头没有换行符,您将得到0

 var regex = /(\\/\\/.*\\r?\\n)*\\"use strict\\";/m; var codeblock = `//hi //there "use strict";`; let match = regex.exec(codeblock); console.log(match.index); 

I also suggest using a regex literal notation /(\\/\\/.*\\r?\\n)*\\"use strict\\";/m rather than the RegExp constructor notation since your pattern is static (no variables are used to build the regex). 我还建议使用正则表达式文字符号 /(\\/\\/.*\\r?\\n)*\\"use strict\\";/m而不是RegExp构造函数表示法,因为您的模式是静态的(没有变量用于构建正则表达式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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