货币匹配“23a”的正则表达式出现意外

Regular expression for currency matching "23a" where unexpected

在 playground 中使用以下代码,我的测试字符串“23a”与我的测试匹配,我不确定为什么。

     extension String {
         var isCurrencyString: Bool {
             return currencyString == self
         }

         var currencyString: String {
             let input = self as NSString

             guard let decimalSeparator = NSLocale.current.decimalSeparator
                 , let groupingSeparator = NSLocale.current.groupingSeparator
                 else { return "" }

             let testPattern = "^-?([0-9]{1,3}(\(groupingSeparator)?[0-9])*)(\(decimalSeparator)?[0-9]{0,2})$"

             guard let expression = try? NSRegularExpression(pattern: testPattern) else { return "" }

             let matches = expression.matches(in: self, options: [], range: NSMakeRange(0, input.length)).map {
                 input.substring(with: [=10=].range)
             }

             return matches.first ?? ""
         }
     }

     let tester = "23a"

     print(tester.currencyString)    //23a
     print(tester.isCurrencyString)  //true

您的问题出在您的第 3 个捕获组。?您需要转义句点,否则它将被解释为任何字符:

guard 
    var decimalSeparator = NSLocale.current.decimalSeparator, 
    var groupingSeparator = NSLocale.current.groupingSeparator
else { return "" }
if groupingSeparator ==  "." { groupingSeparator = #"\."# }
if decimalSeparator ==  "." { decimalSeparator = #"\."# }

您还应该将第二个捕获组中的位数设置为 3

尝试

let testPattern = "^-?([0-9]{1,3}(\(groupingSeparator)?[0-9]{3})*)(\(decimalSeparator)?[0-9]{0,2})$"