gpt4 book ai didi

javascript - 如何在正则表达式构造函数中应用单词边界?

转载 作者:行者123 更新时间:2023-12-02 22:51:24 25 4
gpt4 key购买 nike

export enum KEYWORDS {
CLASS = 1,
METHOD,
FUNCTION,
CONSTRUCTOR,
INT,
BOOLEAN,
CHAR,
VOID,
VAR,
STATIC,
FIELD,
LET,
DO,
IF,
ELSE,
WHILE,
RETURN,
TRUE,
FALSE,
NULL,
THIS
}


setTokenPatterns() {
let keywordString: string = "";
for (let keyword in KEYWORDS) {
var isValueProperty = parseInt(keyword, 10) >= 0;
if (isValueProperty) {
keywordString += KEYWORDS[keyword].toLowerCase() + "|";
}
}

this.keywordRegex = new RegExp(
keywordString.slice(0, keywordString.length - 1)
);

this.tokenPatterns = new RegExp(
this.keywordRegex.source +
"|" +
SYMBOL_REGEX.source +
"|" +
NUMBER_REGEX.source +
"|" +
STRING_REGEX.source +
"|" +
IDENTIFIER_REGEX.source,
"g"
);
}

我有这个程序来获取用于标记我的程序的正则表达式。但问题是 keywordsRegex 匹配像“print”这样的标识符,因为“int”来自 regex 关键字,所以我想为 keywordsRegex 应用字边界。我该怎么做,我知道构造,它是\b,但我不能在 RegExp 构造函数中应用?

最佳答案

您可以在正则表达式中使用\b。您只需将生成的模式包装在非捕获组 (?:) 中,并在正则表达式的开头和结尾添加 \b 即可。

结果看起来像 \b(?:option1|option2|...)\b

示例:

"\\b(?:" +
this.keywordRegex.source +
"|" +
SYMBOL_REGEX.source +
"|" +
NUMBER_REGEX.source +
"|" +
STRING_REGEX.source +
"|" +
IDENTIFIER_REGEX.source +
")\\b"

关于javascript - 如何在正则表达式构造函数中应用单词边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58173836/

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