Custom regular expression operator =~ detail in swift

  • 2020-06-07 05:23:12
  • OfStack

What is a regular expression?

Regular expressions, or regular representations (English: Regular Expression, often abbreviated to 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 syntactic rule. In many text editors, regular expressions are used to retrieve and replace text that fits a pattern.

swift does not yet support regular expressions at the language level, and there may not have been many occasions when app was developed to use regular expressions.

encapsulation

In Cocoa we can use NSRegularExpression for regular matching, so we encapsulate 1 RegularExpHelper match 1 string based on NSRegularExpression to see if it matches a 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 encapsulated RegularExpHelper, we can easily customize the operator.


infix operator =~ : ATPrecedence
precedencegroup ATPrecedence {
 associativity: none
 higherThan: AdditionPrecedence
 lowerThan: MultiplicationPrecedence
}
func =~ (input: String, RegularExp: String) -> Bool {
 do {
  return try RegularExpHelper(RegularExp).match(inpuut: input)
 } catch _ {
  return false
 }
}

Operator definition

infix represents defining 1 middle operator (both before and after input) prefix represents the definition of a preceding operator (preceded by input) postfix represents the definition of a trailing operator (followed by input)

associativity associative law

The order in which multiple operators of the same class appear in order

left (from left to right) right (in order from right to left) none (none by default, not combined)

priority

higherThan has a higher priority than AdditionPrecedence and this is the type of addition lowerThan has a lower priority than MultiplicationPrecedence multiplication and division

Then we can use it


 if "88888888@qq.com" =~ "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
  print(" Comply with email rules ")
 } else {
  print(" Not in line with email rules ")
 }

Pay attention to

Watch out for escape characters when using regular expression strings. The swift operator cannot be defined in a local domain because the operator needs to be used globally. Overloading and custom operators can be risky, so ask yourself if you really need to do it!

conclusion


Related articles: