English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
What are regular expressions?
Regular expressions, also known as regular expressions or conventional expressions (English: Regular Expression, commonly abbreviated as regex, regexp, or RE in code), are a concept in computer science. Regular expressions use a single string to describe and match a series of strings that conform to a certain syntax rule. Regular expressions are often used in many text editors to search for and replace text that matches a certain pattern.
Swift has not yet supported regular expressions at the language level, and there may not be many use cases for regular expressions in app development.
Encapsulation
In Cocoa, we can use NSRegularExpression to perform regular expression matching, so we encapsulate a RegularExpHelper based on NSRegularExpression to match whether a string conforms to a certain regular expression.
struct RegularExpHelper { let RegularExp: NSRegularExpression init(_ pattern: String) throws { try RegularExp = NSRegularExpression(pattern: pattern, options: .caseInsensitive) } func match(inpuut: String) -> Bool { let matches = RegularExp.matches(in: inpuut, options: [], range: NSMakeRange(0, inpuut.count)) return matches.count > 0 } }
Custom =~
With the well-packaged RegularExpHelper, we can conveniently customize operators.
infix operator =~ : ATPrecedence precedencegroup ATPrecedence { associativity: none higherThan: AdditionPrecedence lowerThan: MultiplicationPrecedence } func =~ (input: String, RegularExp: String) -> Bool { do { return try RegularExpHelper(RegularExp).match(input: input) } return false } }
Operator definition
Associativity
That is the calculation order when multiple同类 operators appear in order
Precedence
Then we can use it
if "[email protected]" =~ "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" { print("Meets email rules") } print("Does not meet email rules") }
Note
Summary
That's all for this article. I hope the content of this article has certain reference value for everyone's learning or work. If you have any questions, you can leave a message for communication. Thank you for your support of the Yelling Tutorial.
Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)