验证比特币地址的正则表达式

Regular Expression for Validating Bitcoin Addresses

我正在尝试编写一个函数,如果它是一个有效的比特币地址,returns 是真还是假。

我目前有一个 QR 码扫描器,returns 像这样的字符串:

比特币:18YCdhPsd5gdf6WD4ioMZZJKTNdajUJyTM

这是我的函数:

func isValidBitcoinAddress() -> Bool {
    var fullAddress = self.components(separatedBy: ":")
    let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
    let r2 = self.range(of: pattern, options: .regularExpression)
    if r2 == r {
        return true
    } else {
        return false
    }
}

不幸的是,这每次都返回错误。

我从这个网站得到了正则表达式模式:http://mokagio.github.io/tech-journal/2014/11/21/regex-bitcoin.html

Swift 中的格式可能不同吗?

谢谢!

您只需要在 ::

之后的部分匹配正则表达式
extension String {
    func isValidBitcoinAddress() -> Bool {
        let addressComponents = self.components(separatedBy: ":")
        guard addressComponents.count == 2,
              addressComponents[0] == "bitcoin" else {
            return false
        }

        let address = addressComponents[1]

        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let range = address.range(of: pattern, options: .regularExpression)
        return range == address.indices
    }
}

您正在将 self 与模式而不是 fullAddress[1] 进行比较。

使用以下内容:

func isValidBitcoinAddress() -> Bool {
    let fullAddress = self.components(separatedBy: ":")
    if fullAddress.count == 2 && fullAddress[0] == "bitcoin" {
        let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"
        let r = fullAddress[1].startIndex..<fullAddress[1].endIndex
        let r2 = fullAddress[1].range(of: pattern, options: .regularExpression)
        return r == r2
    } else {
        return false
    }
}

@rmaddy 和@Alexander 已经回答了你的问题。

我只是添加我实现的代码:

func isValidBitcoinAddress(stringBitCoinID:String) -> Bool {
    let fullAddress = stringBitCoinID.components(separatedBy: ":")

    guard fullAddress.count == 2, fullAddress[0] == "bitcoin" else {
        return false
    }

    let r = fullAddress[1]
    let pattern = "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"

    let bitCoinIDTest = NSPredicate(format:"SELF MATCHES %@", pattern)
    let result = bitCoinIDTest.evaluate(with: r)

    return result
}