在编译原理中,正则分词是一种常用的词法分析方法,它通过正则表达式来定义词法单元(Token)的模式,并将源代码中的字符序列转换为词法单元序列。在正则分词中,我们需要定义一个包含各种词法单元模式的正则表达式,然后将源代码中的字符序列与正则表达式进行匹配。如果匹配成功,则将匹配的字符序列转换为对应的词法单元。
例子:通过正则表达式将算数运算符解析成词法单元
tokenize.js
let RegExpObj = /([0-9]+)|([ ])|(\+)|(\-)|(\*)|(\/)|([\(])|([\)])/g; // 匹配规则
let tokenTypes = require("./tokenTypes"); // token的type
let tokenNames = [
tokenTypes.NUMBER,
tokenTypes.SPACE,
tokenTypes.PLUS,
tokenTypes.MINUS,
tokenTypes.MULTIPLY,
tokenTypes.DIVIDE,
tokenTypes.LEFTBRACKET,
tokenTypes.RIGHTBRACKET,
];
// script = 1+2+3*4-2/1
// 组装tokens
function tokenize(script) {
let tokens = [];
for (let token of tokenizer(script)) {
tokens.push(token);
}
return tokens;
}
// 生成器函数处理每一个token
function* tokenizer(script) {
let result;
while (true) {
debugger;
result = RegExpObj.exec(script);
if (!result) break;
let token = {};
let index = result.findIndex((item, index) => index > 0 && !!item);
token.type = tokenNames[index - 1];
token.value = result[0];
yield token;
}
}
console.log(tokenize("1+2+3*4-2/1"));
tokenTypes.js
const NUMBER = "NUMBER"; // 数字
const SPACE = "SPACE"; // 空格
const PLUS = "PLUS"; // +
const MINUS = "MINUS"; // -
const MULTIPLY = "NULTIPLY"; // *
const DIVIDE = "DIVIDE"; // /
const LEFTBRACKET = "LEFTBRACKET"; // (
const RIGHTBRACKET = "RIGHTBRACKET"; // )
module.exports = {
NUMBER,
SPACE,
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
LEFTBRACKET,
RIGHTBRACKET,
};
tokens
[
{ type: 'NUMBER', value: '1' },
{ type: 'PLUS', value: '+' },
{ type: 'NUMBER', value: '2' },
{ type: 'PLUS', value: '+' },
{ type: 'NUMBER', value: '3' },
{ type: 'NULTIPLY', value: '*' },
{ type: 'NUMBER', value: '4' },
{ type: 'MINUS', value: '-' },
{ type: 'NUMBER', value: '2' },
{ type: 'DIVIDE', value: '/' },
{ type: 'NUMBER', value: '1' }
]