Swift将javascript regualr表达式转换为ios正则表达式

时间:2018-09-24 05:10:32

标签: ios swift regex

JavaScript中的正则表达式:(^04[0-9]{8})|(^[0-9]{2}[0-9]{4}[0-9]{4}$)

我正在尝试对未验证的澳大利亚电话使用正则表达式。如何将该正则表达式转换为iOS正则表达式?

let Format = "^04[0-9]{8})|(^[0-9]{2}[0-9]{4}[0-9]{4}$"
let Predicate = NSPredicate(format: "SELF MATCHES %@", Format)
return Predicate.evaluate(with: fieldText)

1 个答案:

答案 0 :(得分:0)

我认为您在开头和结尾仅缺少括号()

let fieldText = "0401234567"
let pattern = "(^04[0-9]{8})|(^[0-9]{2}[0-9]{4}[0-9]{4}$)"
let matches = fieldText.range(of: pattern, options: .regularExpression) != nil
print(matches) // true

或者,用NSPredicate

let fieldText = "0401234567"
let pattern = "(^04[0-9]{8})|(^[0-9]{2}[0-9]{4}[0-9]{4}$)"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
let matches = predicate.evaluate(with: fieldText)
print(matches) // true

尽管正则表达式看起来仍然很奇怪。