阿晨1998
2023-05-19 15:03:03
所以說到正則表達(dá)式我javascript,我只知道1%左右。我正在嘗試編寫一些代碼來檢測數(shù)學(xué)表達(dá)式(例如 2 + 3)。前段時間我在另一個問題上發(fā)現(xiàn)了這個:/(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/I這似乎工作正常,但我只希望它在前面有特定關(guān)鍵字時工作。所以現(xiàn)在我有這樣的東西:var re = /(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/i;var str = "2 + 2";console.log(str.match(re));但我想要這個:var keyword = "Some keyword ";var str = `${keyword}2 + 2`;//Regular expressio that should only work if "Some keyword" and math expression are therevar re = //the expression//should match the stringconsole.log(str.match(re));//But if the keiword is not therevar keyword = "";var str = `${keyword}2 + 2`;//Regular expressio that should only work if "Some keyword" and math expression are therevar re = //the expression//should NOT match the stringconsole.log(str.match(re));我試過這個,但它并沒有真正達(dá)到我的預(yù)期:var one = /Some keyword /i;var two = /(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/i;var one_or_two = new RegExp("(" + one.source + ")?(" + two.source + ")")var str = "Some keyword 2 + 1";alert(str.match(one_or_two))我需要在正則表達(dá)式中使用所有這些,因為我不能使用 str.match(re)有沒有辦法做到這一點(diǎn)?無論如何提前感謝。
1 回答

30秒到達(dá)戰(zhàn)場
TA貢獻(xiàn)1828條經(jīng)驗 獲得超6個贊
您的two正則表達(dá)式包含一個^斷言,該斷言阻止了關(guān)鍵字后的匹配。
下面是您的最后一次嘗試,更正了此錯誤,為公式命名捕獲并添加了整個字符串,并刪除了問號,因此現(xiàn)在需要“Some keyword”。此外,由于標(biāo)志,我替換[eE]為, : ei
var one = /Some keyword /i;
var two = /(?:(?:|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:e[+-]?\d+)?\s*))+$/i;
var one_or_two = new RegExp("(?<whole>(" + one.source + ")(?<formula>" + two.source + "))")
var str = "Some keyword 2 + 1";
if (match = str.match(one_or_two)) {
console.log(match.groups.formula); // Only the formula.
console.log(match.groups.whole); // The whole string.
}
添加回答
舉報
0/150
提交
取消