gpt4 book ai didi

javascript - 无法制作动态增长的正则表达式

转载 作者:行者123 更新时间:2023-11-28 17:46:38 24 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中构建一个正则表达式来匹配算术运算的部分内容。例如,以下是一些输入和预期输出:

What is 7 minus 5?          >> ['7','minus','5']
What is 6 multiplied by -3? >> ['6','multiplied by', '-3']

我有这个有效的正则表达式:/^什么是(-?\d+)(减|加|乘|除)(-?\d+)\?$/

现在我想扩展一些东西来捕获额外的操作。例如:

What is 7 minus 5 plus 3?  >> ['7','minus','5','plus','3']

所以我用了:^什么是(-?\d+)(?:(减|加|乘|除)(-?\d+))+\?$。但它产生:

What is 7 minus 5 plus 3?  >> ['7','plus','3']

为什么跳过负5?我该如何将其包含在我想要的结果中? (here is my sample)

最佳答案

您面临的问题来自这样一个事实:捕获组只能返回一个值。如果同一个捕获组有多个值(就像您的情况一样),它将始终返回最后一个值。

我喜欢 http://www.rexegg.com/regex-capture.html#spawn_groups 的解释方式

The capturing parentheses you see in a pattern only capture a single group. So in (\d)+, capture groups do not magically mushroom as you travel down the string. Rather, they repeatedly refer to Group 1, Group 1, Group 1… If you try this regex on 1234 (assuming your regex flavor even allows it), Group 1 will contain 4—i.e. the last capture.

In essence, Group 1 gets overwritten every time the regex iterates through the capturing parentheses.

因此,技巧是使用带有全局标志 (g) 的正则表达式,并多次执行该表达式,当使用 g 标志时,以下执行从上一次结束的地方开始。

我制作了一个正则表达式来向您展示策略,隔离公式,然后迭代,直到找到所有内容。

var formula = "What is 2 minus 1 minus 1";
var regex = /^What is ((?:-?\d+)(?: (?:minus|plus|multiplied by|divided by) (?:-?\d+))+)$/

if (regex.exec(formula).length > 1) {
var math_string = regex.exec(formula)[1];
console.log(math_string);
var math_regex = /(-?\d+)? (minus|plus|multiplied by|divided by) (-?\d+)/g
var operation;
var result = [];
while (operation = math_regex.exec(math_string)) {
if (operation[1]) {
result.push(operation[1]);
}
result.push(operation[2], operation[3]);
}
console.log(result);
}

另一个解决方案,如果您不需要任何花哨的东西,那就是删除“什么是”,将乘以替换为multiplied_by(与除法相同)并拆分空格上的字符串。

var formula = "What is 2 multiplied by 1 divided by 1";
var regex = /^What is ((?:-?\d+)(?: (?:minus|plus|multiplied by|divided by) (?:-?\d+))+)$/

if (regex.exec(formula).length > 1) {
var math_string = regex.exec(formula)[1].replace('multiplied by', 'multiplied_by').replace('divided by', 'divided_by');
console.log(math_string.split(" "));
}

关于javascript - 无法制作动态增长的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565717/

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