有没有办法从正则表达式中匹配和删除逻辑运算符
在 Regex 中使用 Match 函数时,我不想包含逻辑运算符(和、或、非)。我在下面尝试过,但没有按预期工作。有人可以帮帮我吗。
我用于解析的字符串排序:示例:
1. Input -->'(Value1==6) and (Value2==0)?1:0'
Output --> ["Value1", "Value2"]
2. Input : 'Value_1'
Output -->["Value_1"]
3. Input : '(Value_1 * Value_2)'
Output : ["Value1", "Value2"]
4. Input : 'Value_Machine_Outcome==4?1:0'
Output : Value_Machine_Outcome
嵌套条件:否
条件是否总是在括号中:不,
我正在使用Math.evaluate在下一步评估它们
请举例如下:
1. Input -->'(Value1==6) and (Value2==0)?1:0'
Output --> ["Value1", "Value2"]
2. Input : 'Value_1'
Output -->["Value_1"]
3. Input : '(Value_1 * Value_2)'
Output : ["Value1", "Value2"]
4. Input : 'Value_Machine_Outcome==4?1:0'
Output : Value_Machine_Outcome
回答
您更新的问题完全改变了输入的性质。如果输入是多种多样的,您将需要匹配几乎所有不以不是and, or, or的数字开头的“单词” not(但这符合您的原始尝试,所以我想这是有道理的) :
const regex = /(?!and|or|not)b[A-Z]w*/gi;
const regex = /(?!and|or|not)b[A-Z]w*/gi;
现场示例:
这通过禁止and,or和not并要求在单词边界 ( b)处进行匹配来实现。请注意,在测试中,我将Value_Machine_Outcome==4?1:0字符串的预期结果更改为数组,而不仅仅是字符串,就像所有其他字符串一样。
问题之前的原始答案完全改变了输入:
如果您想使用String.prototype.match,您可以对 a 使用正向后视(自 ES2018 起)(并匹配 a 之前的所有=内容:
const regex = /(?<=()[^=]+/g;
const regex = /(?<=()[^=]+/g;
现场示例:
const tests = [
{
str: "(Value1==6) and or not (Value2==0)?1:0",
expect: ["Value1", "Value2"]
},
{
str: "Value_1",
expect: ["Value_1"]
},
{
str: "(Value_1 * Value_2)",
expect: ["Value_1", "Value_2"]
},
{
str: "Value_Machine_Outcome==4?1:0",
expect: ["Value_Machine_Outcome"] // Note I put this in an array
}
];
const regex = /(?!and|or|not)b[A-Z]w*/gi;
for (const {str, expect} of tests) {
const result = str.match(regex);
const good = result.length === expect.length && result.every((v, i) => v === expect[i]);
console.log(JSON.stringify(result), good ? "Ok" : "<== ERROR");
}
如果您对循环没问题,则可以通过使用捕获组来避
const regex = /(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
found.push(match[1]);
}
const regex = /(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
found.push(match[1]);
}
免后视(因为它们仅在 ES2018 中添加):
现场示例:
在评论中你问:
我的表达式也可以包含下划线。就像它可能是 value_1、value_2。它会在那里工作吗?
我说会,因为上面两个都匹配,但不匹配=.
后来你说:
当我的结构包含“Value_1”时,它会忽略
同样,上述两种方法都可以与Value_1和 一起使用Value_2:
第一的:
const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /(?<=()[^=]+/g;
const found = paragraph.match(regex);
console.log(found);
// expected output: Array ["Value1", "Value2"]
第二: