2 回答

TA貢獻1796條經驗 獲得超4個贊
試試這個正則表達式:([a-zA-Z]+[a-zA-Z0-9_]+)(?<![and|or|not]). 我剛剛更新了您的代碼中的正則表達式,請測試并讓我知道您是否有任何疑問。
const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /([a-zA-Z]+[a-zA-Z0-9_]+)(?<![and|or|not])/g;
const found = paragraph.match(regex);
console.log(found);

TA貢獻1827條經驗 獲得超9個贊
您更新的問題完全改變了輸入的性質。如果輸入如此不同,您將需要匹配任何不以 、 或 以外的數字開頭的“單詞” and
(or
但這not
符合您最初的嘗試,所以我想這是有道理的) :
const regex = /(?!and|or|not)\b[A-Z]\w*/gi;
實例:
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");
}
其工作原理是不允許and
、or
、 和not
,并要求在單詞邊界 ( \b
) 處進行匹配。請注意,在測試中,我將Value_Machine_Outcome==4?1:0
字符串的預期結果更改為數組,而不僅僅是字符串,就像所有其他結果一樣。
問題完全改變輸入之前的原始答案:
如果你想使用String.prototype.match
,你可以對 a 使用正向后視(自 ES2018 起)(
并匹配 a 之前的所有內容=
:
const regex = /(?<=\()[^=]+/g;
實例:
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"]
如果您同意循環,則可以通過使用捕獲組來避免后向查找(因為它們僅在 ES2018 中添加):
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
found.push(match[1]);
}
實例:
const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
found.push(match[1]);
}
console.log(found);
// expected output: Array ["Value1", "Value2"]
在評論中你問:
我的表達式也可以包含下劃線。就像它可以是 value_1、value_2 一樣。那里能行得通嗎?
我說會是因為上面的兩個都匹配除了=
.
后來你說:
當我的結構包含“Value_1”時它會忽略
同樣,以上兩者都可以與Value_1
和配合使用Value_2
:
第一的:
const paragraph = '(Value_1==6) and (Value_2==0)?1:0';
const regex = /(?<=\()[^=]+/g;
const found = paragraph.match(regex);
console.log(found);
// expected output: Array ["Value1", "Value2"]
第二:
const paragraph = '(Value_1==6) and (Value_2==0)?1:0';
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
found.push(match[1]);
}
console.log(found);
// expected output: Array ["Value1", "Value2"]
添加回答
舉報