正则实现数字运算的方法

好久没写过了,最近在项目中有一个用到数字计算的功能,就想着写下,记下来,以后好歹还能看到,因为之前搜索IOS算式并没有什么方法能够实现比如 1+23/3(3+3) 这种运算,我就想到通过正则的方式去计算,因为算式长度不限,数值不限,所以最简单的方法就是正则了,但是网上又没有这种算法,所以就根据java的正则计算公式,写出来iOS的正则计算公式.

借鉴java代码来源:https://blog.csdn.net/qq_41819893/article/details/127780029

好了废话不多,上主菜:

首先定义下正则,然后定义下需要的运算符

private static let SYMBOL = "\\+|-|\\*|/|\\(|\\)|\\%"
    
    private static let LEFT = "("
    private static let RIGHT = ")"
    private static let ADD = "+"
    private static let MINUS = "-"
    private static let TIMES = "*"
    private static let DIVISION = "/"
    private static let REMAINDER = "%"
    
    private static let LEVEL_01 = 1
    private static let LEVEL_02 = 2
    private static let LEVEL_HIGH = Int.max
    
    private var stack: [String] = []
    private var data: [String] = []

其次就是进行字符串的拆分了

func replaceAllBlank(_ s: String) -> String {
        return s.replacingOccurrences(of: "\\s+", with: "", options: .regularExpression)
    }
    
    func isNumber(_ s: String) -> Bool {
        let pattern = "^[-\\+]?[.\\d]*$"
        return s.range(of: pattern, options: .regularExpression) != nil
    }
    
    func isSymbol(_ s: String) -> Bool {
        return s.range(of: MLC_ReversePolishCalculator.SYMBOL, options: .regularExpression) != nil
    }

之后就要将运算的优先级区分下

func calcLevel(_ s: String) -> Int {
        if s == MLC_ReversePolishCalculator.ADD || s == MLC_ReversePolishCalculator.MINUS {
            return MLC_ReversePolishCalculator.LEVEL_01
        } else if s == MLC_ReversePolishCalculator.TIMES || s == MLC_ReversePolishCalculator.DIVISION || s == MLC_ReversePolishCalculator.REMAINDER {
            return MLC_ReversePolishCalculator.LEVEL_02
        }
        return MLC_ReversePolishCalculator.LEVEL_HIGH
    }

重点来了啊

func doTheMath(_ s1: String, _ s2: String, _ symbol: String) -> Double {
        switch symbol {
        case MLC_ReversePolishCalculator.ADD: return Double(s1)! + Double(s2)!
        case MLC_ReversePolishCalculator.MINUS: return Double(s1)! - Double(s2)!
        case MLC_ReversePolishCalculator.TIMES: return Double(s1)! * Double(s2)!
        case MLC_ReversePolishCalculator.DIVISION: return Double(s1)! / Double(s2)!
        case  MLC_ReversePolishCalculator.REMAINDER: return Double(Double(s1)!.truncatingRemainder(dividingBy: Double(s2)!))
        default: return 0
        }
    }
    
    func run(_ math: String) {
        do {
            _ = try doCalc(doMatch(math))
  
        } catch {
            MLC_Log.log(error, level: 99)
        }
    }

以上就是我写的代码中的部分内容 ,除了怎么处理那块的东西我没发 其他的都发出来了。一滴都没有了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。