簡體   English   中英

Javascript Regex,如果沒有,則在數學運算符前后添加空格

[英]Javascript Regex, Add space before and after math operators if there is none

我正在嘗試為我的不和諧機器人制作完美的數學解析器。

目前我有一個簡單的函數解析器,它接受一個字符串,它有大量的.replace方法來清除一堆垃圾或格式化遺留的不和諧內容,或者只是用 () 和這樣的生活質量替換 {} 。 .

var parseArgs = args.toLowerCase().replace(/ -o/g, "").replace(/x/g, "*").replace(/[a-z]/g, "")
    .replace(/{/g, "(").replace(/}/g, ")").replace(/\[/g, "(").replace(/]/g, ")").replace(/\+=/g, "+")
    .replace(/-=/g, "-").replace(/'/g, "").replace(/`/g, "").replace(/"/g, "");

var origArgs = args.toLowerCase().replace(/`/g, "").replace(/ -o/g, "");

const output = parseMath(parseArgs);

這很好,但是如果你輸入這樣的方程:
!math 1 + 1aaa+aaaa2{55>>2}

解析器將輸出:
1 + 1+2*(55>>2)

我希望它輸出:
1 + 1 + 2 * (55 >> 2)

這很容易被我的函數解析,但方程被發送到聊天中,而且非常難看。

我問是否有一個簡單的正則表達式來檢查數學運算符( + - / * x ( ) >> ^ += -= == === )是否在任何數字之間

所以1+2/3(4>>2)3>>4===3*4將分別變成1 + 2 / 3 (4 >> 2)3 >> 4 === 3 * 4

編輯:我看到我的替換是多么糟糕,所以我簡化了它們:

var parseArgs = args.toLowerCase().replace(/x/g, "*").replace(/ -o|[a-z]|"|'|`/g, "")
    .replace(/{|\[/g, "(").replace(/}|]/g, ")").replace(/\+=/g, "+").replace(/-=/g, "-");
var origArgs = args.toLowerCase().replace(/ -o|`/g, "");

首先刪除任何不是數學的東西(刪除任何不是數字或可能的運算符),然后使用.replace匹配零個或多個空格,后跟任何運算符,然后再次匹配零個或多個空格,然后用每邊一個空格替換操作符:

 const parse = (args) => { const argsWithOnlyMath = args.replace(/[^\\d+\\-\\/*x()>^=]/g, ' '); const spacedArgs = argsWithOnlyMath .replace(/\\s*(\\D+)\\s*/g, ' $1 ') // add spaces .replace(/ +/g, ' ') // ensure no duplicate spaces .replace(/\\( /g, '(') // remove space after ( .replace(/ \\)/g, ')'); // remove space before ) console.log(spacedArgs); }; parse('!math 1 + 1aaa+aaaa2(55>>2)'); parse(' 1+2/3(4>>2) '); parse('3>>4===3*4');

要在()之前添加空格,只需添加更多.replace s:

 const parse = (args) => { const argsWithOnlyMath = args.replace(/[^\\d+\\-\\/*x()>^=]/g, ' '); const spacedArgs = argsWithOnlyMath .replace(/\\s*(\\D+)\\s*/g, ' $1 ') // add spaces .replace(/\\(/g, ' (') // add space before ( .replace(/\\)/g, ') ') // add space after ) .replace(/ +/g, ' ') // ensure no duplicate spaces .replace(/\\( /g, '(') // remove space after ( .replace(/ \\)/g, ')'); // remove space before ) console.log(spacedArgs); }; parse('!math 1 + 1aaa+aaaa2(55>>2)'); parse(' 1+2/3(4>>2) *()'); parse('3*()');

暫無
暫無

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

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