繁体   English   中英

使用Node.js在JavaScript文件中将正则表达式与斜杠(分隔)区分开

[英]Distinguishing regexes from a slash (division) in a JavaScript files with Node.js

我试图通过将其作为Node.js中的缓冲区读取并逐个遍历字符来区分JavaScript文件中的正则表达式(/ complex regex here /)与除法(/)。 原因

const fs = require('fs');
const buf = fs.readFileSync('sample.js');
const slash = '/'.codePointAt(0);
const backSlash = '\\'.codePointAt(0);
let escaped = false;
for(let key of buf.keys()) {
    if(buf[key] === slash && !escaped) {
        // How do I distinguish this slash? Is it a regex or is it a division sign?
    }
    if(escaped) {
        escaped = false;
    } else if(buf[key] === backSlash) {
        escaped = true; // set escaped to true to ignore the next character.
    }
}

该文件中没有注释,因此我不必担心///**/

我应该如何区分分隔符号和正则表达式?

使用Esprima的标记器功能:

var esprima = require('esprima');
var tokens = esprima.tokenize('var regex = /foo/bar; var math = 1 / 2');
console.log(tokens);

并且您将获得以下输出:

[ { type: 'Keyword', value: 'var' },
  { type: 'Identifier', value: 'regex' },
  { type: 'Punctuator', value: '=' },
  { type: 'RegularExpression',
    value: '/foo/bar',
    regex: { pattern: 'foo', flags: 'bar' } },
  { type: 'Punctuator', value: ';' },
  { type: 'Keyword', value: 'var' },
  { type: 'Identifier', value: 'math' },
  { type: 'Punctuator', value: '=' },
  { type: 'Numeric', value: '1' },
  { type: 'Punctuator', value: '/' },
  { type: 'Numeric', value: '2' } ]

如您所见,令牌生成器正确地将前两个斜杠标识为正则表达式的一部分,并将最后一个斜杠标识为除法运算符。

暂无
暂无

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

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