本文介绍了Swift正则表达式格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉pcre正则表达式,但它们似乎并不适用于swift。

I'm familiar with doing pcre regexes, however they don't seem to work in swift.

^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$

验证数字,如1,000,000.00

to validate numbers like 1,000,000.00

但是把它放在我的swift函数中会导致错误。

However, putting this in my swift function, causes an error.

    extension String {
    func isValidNumber() -> Bool {
        let regex = NSRegularExpression(pattern: "^([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$", options: .CaseInsensitive, error: nil)
        return regex?.firstMatchInString(self, options: nil, range: NSMakeRange(0, countElements(self))) != nil
    }
}

无效在litteral中的转义序列

"Invalid escape sequence in litteral"

这当然是因为pcre使用了\字符,swift将其解释为逃避(我相信?)

This is of course, because pcre uses the "\" character, which swift interprets as an escape (I believe?)

因为我不能只使用我习惯的正则表达式。如何将它们翻译为与Swift代码兼容?

So since I can't just use the regexes I'm used to. How do I translate them to be compatible with Swift code?

推荐答案

在双引号中,单个反斜杠将作为转义被引用序列。你需要再次转义所有反斜杠才能将其视为正则表达式反斜杠字符。

Within double quotes, a single backslash would be readed as an escape sequence. You need to escape all the backslashes one more time in-order to consider it as a regex backslash character.

"^([1-9]\\d{0,2}(,\\d{3})*|([1-9]\\d*))(\\.\\d{2})?$"

这篇关于Swift正则表达式格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:07