ios - 从字符串中提取货币和价格值

标签 ios objective-c swift

我正在尝试找到一种从字符串中提取货币和价格值的好方法。它应该适用于多种货币。零件……

  • 提取数字 – 可以是整数或十进制值
  • 检测附近的货币符号以将其与货币代码相匹配
  • 忽略不是价格的数字——例如不附加货币指标

例子

  • “苹果、2 个橙子和草莓 5.0 欧元”
  • “苹果、32 个橙子和草莓 5.0 欧元”
  • “苹果、橙子 5 欧元和草莓”
  • “5 欧元的苹果、橙子和草莓”

结果

  • 价格为:5.0
  • 货币代码和符号:€ (EUR)

另一个例子

  • “苹果、32 个橙子和草莓 5.0 美元”→ 数字:5.0,货币美元 (USD)

处理不同货币的好方法是什么?

最佳答案

您可以为此使用正则表达式。我在我的框架中使用以下内容:

class Regex {
  private let internalExpression: NSRegularExpression
  let pattern: String
  var groups:[String]? = nil

  init(_ pattern: String) {
    self.pattern = pattern
    let regex: NSRegularExpression?
    do {
      regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
    } catch let error as NSError {
      fatalError("Invalid pattern '\(pattern)` (\(error))")
    }
    internalExpression = regex!
  }

  init(_ pattern: String, options: NSRegularExpressionOptions) {
    self.pattern = pattern
    let regex: NSRegularExpression?
    do {
      regex = try NSRegularExpression(pattern: pattern, options: options)
    } catch let error as NSError {
      fatalError("Invalid pattern '\(pattern)` (\(error))")
    }
    internalExpression = regex!
  }

  func test(input: String) -> Bool {
    let matches = self.internalExpression.matchesInString(input, options: [], range:NSMakeRange(0, input.characters.count)) as [NSTextCheckingResult]
    if matches.count == 0 { groups = nil; return false }
    if internalExpression.numberOfCaptureGroups > 0 {
      groups = [String]()
      let match = matches[0] as NSTextCheckingResult
      for index in 1..<match.numberOfRanges {
        let range = match.rangeAtIndex(index)
        if range.location == 9223372036854775807 { groups!.append("") }
        else { groups!.append((input as NSString).substringWithRange(range)) }
      }
    }
    return true
  }

  func match(index:Int) -> String? {
    return groups![index]
  }
}

然后你可以检查

let regexEuro = Regex("(\\d+(\\.\\d+)?) *€")
let regexDollar = Regex("\\$ *(\\d+(\\.\\d+)?)")
if regexEuro.test("This is 20 € ...") {
  print(regexEuro.match(0))
}
if regexDollar.test("This is $ 20.3 ...") {
  print(regexDollar.match(0))
}

关于ios - 从字符串中提取货币和价格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148507/

相关文章:

ios - 更改 UITableViewCell 中元素的动态高度约束

ios - Safari web 检查器只显示源、控制台和审计

iphone - 核心数据和多线程编程

iphone - MPMoviePlayerController 在连续视频之间产生闪烁

ios - 枚举 UITableViewCell

ios - swift - "must register a nib or a class for the identifier or connect a prototype cell in a storyboard"

ios - 呈现的 View Controller 在使用自定义 UIViewController 动画制作动画后消失

ios - 如何从 iOS 中的 CFStream 获取远程地址?

ios - UITableview 项目向上滚动后变为粗体

iphone - UIButton 图像未更改/更新