Some methods of using regular expressions in Swift _swift

Source: Internet
Author: User

I've been using Swift for a while, but the most depressing thing is that it doesn't support regular expressions.

First of all, this is really a new language, I have comments on the Web site a radar (rdar://17257306 for Apple folks). If you agree with this view, please support it.

What I mean by regular expressions is this (Ruby code):

If name =~/ski$/
 puts ' #{name} is probably Polish '
end

If you want to query quickly, you can use the =~ operator to return a matching result. In addition, use the/pattern/syntax form to directly use regular. except/symbol needs to be escaped, no other symbols are affected:

 
Url_pattern =/^https?:\ /\/.*/


This is much better than using \ Escape (which is common in regular use). If the string is used in the regular, it looks bad. This is the OBJECTIVE-C code:

Copy Code code as follows:
Nsregularexpression *regex = [nsregularexpression
regularexpressionwithpattern:@ "\\s+\\w{4,10}\\s\\d+"
options:0
Error:nil];

Escaping each \ symbol makes the code less readable. Not to mention the creation of extra classes.  Of course, if you need more robust regular functionality, you have to develop a full set of specific implementation classes. But in general terms (common in scripting languages) is a bit of a fuss.

What does Swift do with it?

Swift does not currently provide support for regular syntax and classes, so it can only be implemented using the Nsregularexpression mentioned earlier.

But we can consider using Swift's super operator to implement it. Consider the following scenario:

Copy Code code as follows:

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)-> Bool {
Let matches = self.internalExpression.matchesInString (input, Options:nil, Range:nsmakerange (0, countelements (input)) )
return matches.count > 0
}
}

This requires a lot of assumption validation when using Nsregularexpression. It's a lot simpler if you use another method:

Copy Code code as follows:

If Regex ("\\w{4}"). Test ("ABCD") {
println ("matches pattern")
}

It's still unavoidable to use string escapes, but it's much better than using native nsregularexpression.

=~ operator

After studying the method of step Christopher, I want to change the operator function by myself. It looks pretty simple:

Copy Code code as follows:

Operator infix =~ {}

This defines the position of the operator, like manipulating two elements rather than between them, but before or after an element (like the + + operation). The following defines a function that uses the operator:

Copy Code code as follows:

Func =~ (input:string, pattern:string)-> Bool {
return Regex (pattern). Test (input)
}

The complex parts are ready-made and we simply need to invoke them.

Finally, use the regular test results as follows:

Copy Code code as follows:

Let PhoneNumber = "(800) 555-1111"
If PhoneNumber =~ "(? \\d{3})? \\s\\d{3}-\\d{4}" {
println ("That looks like a valid US phone number")
}

I think this is a good result, and if one day Apple finds out about this regular implementation of my grammar/regex/literal syntax, I'm happy to support it.

Update

A helpful Hacker news critic points to a direction that is closer to where I want to be, but uses the existing APIs:

Copy Code code as follows:

If let match = name.rangeofstring ("ski$", Options:. Regularexpressionsearch) {
println ("\ (name) is probably Polish")
}

Yes, I don't know this, and it looks very useful.

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.