簡體   English   中英

使用正則表達式拆分一元運算符

[英]Unary operator split using regex

有很多相關的正則表達式問題,但沒有一個能解決我的問題,因為我的表達式中沒有括號。

我有一個字符串數學表達式,例如: 1*2+3-99/50

我需要標記表達式以將表達式轉換為后修復符號。 所以我使用 split 和 regex 如下:

'1*2+3-99/50'.split(/([+\-*/])/)                   // operands have no unary (-)
// ['1', '*', '2', '+', '3', '-', '99', '/', '50'] 

這很好用。 但是使用一元運算符,它不起作用。 所以我嘗試使用前瞻來檢測減號是否出現在另一個運算符之后:

'1*-2+-3--99/-50'.split(/([+\-*/])(?=-)/               // all operands have unary (-)
// ['1', '*', '-2', '+', '-3', '-', '-99', '/', '-50']

這也有效,但只是因為所有數字都已經有負號。

我曾嘗試首先使用一元 (-) 運算符捕獲操作數以將其附加到最終標記,但我丟失了在評估階段很重要的順序。 還嘗試閱讀條件正則表達式,但在我的情況下沒有多大意義。

是否可以在一次拆分中拆分包含負號的令牌?

嘗試用\\b分割

 var a = '1*-2+-3-99/-50'.split(/(\\b[-+*/])/); console.log(JSON.stringify(a))

首先,你真的不想用正則表達式來做這件事。 重要的是,您需要跟蹤操作的順序,這是 postfix 可以認為是理所當然的,但 infix 不能。

此示例代碼使用正則表達式,但這不是真正的邏輯所在:

 function toPostfix(equation) { let output = ""; let additions = equation.replace(/\\b\\s*-/g, "+-").split(/\\+/); if (additions.length > 1) { output = "+)"; for (let a = additions.length - 1; a >= 0; a--) { output = toPostfix(additions[a]) + " " + output; } return "( " + output; } else { if (equation.match(/^1\\/-?[0-9]+$/)) { return "( 1 " + equation.substring(2) + " /)"; } let multiplications = equation.replace(/\\//g, "*1/").split(/\\*/); if (multiplications.length > 1) { output = "*)"; for (let m = multiplications.length - 1; m >= 0; m--) { output = toPostfix(multiplications[m]) + " " + output; } return "( " + output; } else { return equation; } } } console.log(toPostfix('1*2+3-99/50')); // "( ( 1 2 *) 3 ( -99 ( 1 50 /) *) +)"

為簡單起見,這將減法轉換為負數的加法,並將除法轉換為倒數 ( 1/n ) 的乘法。 為了觀察運算順序,我們必須先按加法/減法進行拆分,然后再分解為每個乘法/除法。 我使用遞歸調用來分解每個部分並從右到左逐步建立答案。

僅占+ - */ 沒有括號,沒有指數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM