所以說到正則表達式我javascript,我只知道1%左右。我正在嘗試編寫一些代碼來檢測數學表達式(例如 2 + 3)。前段時間我在另一個問題上發現了這個:/(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/I這似乎工作正常,但我只希望它在前面有特定關鍵字時工作。所以現在我有這樣的東西: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));我試過這個,但它并沒有真正達到我的預期: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))我需要在正則表達式中使用所有這些,因為我不能使用 str.match(re)有沒有辦法做到這一點?無論如何提前感謝。
用于測試同一字符串中的關鍵字和數學表達式的 Javascript 正則表達式
阿晨1998
2023-05-19 15:03:03