gpt4 book ai didi

javascript - 从 JavaScript 代码中获取 token

转载 作者:行者123 更新时间:2023-11-30 00:11:42 26 4
gpt4 key购买 nike

我想用 JavaScript/Node.js 编写一个简单的解释器。我在生成 token 时遇到了障碍。

var code = 'if (a > 2 && b<4) c = 10;';

code.match(/\W+/g)
// [" (", " > ", " && ", "<", ") ", ";"]

code.match(/\w+/g)
// ["if", "a", "2", "b", "4", "elo"]

如图所示,W+ 让我获取特殊字符,w+ 让我获取单词。我想知道如何将它们放在一个数组中,如下所示:

// ["if", "(", "a", ">", "2", "&&", "b", "<", "4", ")", "c", "=", "10", ";"]

最佳答案

As shown, W+ lets me get special characters and w+ lets me get words. I wonder how to get those in one array, something like below:

试试这个

code.match(/\w+|\W+/g)

输出为

["if", " (", "a", " > ", "2", " && ", "b", "<", "4", ") ", "c", " = ", "10", ";"]

这也会 trim 标记

var tokens = code.match(/\w+|\W+/g).map(function(value){return value.trim()});

关于javascript - 从 JavaScript 代码中获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36219055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com