Swift uses regular expressions

Source: Internet
Author: User



Usually use a common regular class


 
 
class Regex {
    let internalExpression: NSRegularExpression
    let pattern: String
    init(_ pattern: String) {
        self.pattern = pattern
        var error: NSError?
        self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
    }
    func test(input: String) -> Array<String>{
        let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input))) as Array<NSTextCheckingResult>
        if (matches.count>0) {
            var values:Array<String> = []
            for result in matches {
                for i in 0...(result.numberOfRanges-1) {
                    let range = result.rangeAtIndex(i)
                    var nsinput = input as NSString
                    values += [nsinput.substringWithRange(NSRange(location: range.location,length: range.length))]
                }
            }
            //println(values)
            return values
        }else{
            return []
        }
    }
}


The regular expression is \d in double quotation marks to write \\d, such as Take 5 numbers "\\d{5}".



For example, take 3-30 characters (including numbers or letters or-) to write a


 
var matchResult = Regex("[\\d\\w-]{2,30}").test(domainInput.text)
        if !matchResult.isEmpty {
    println(matchResult[0])
}





Swift uses regular expressions


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.