Home>

Regular expressions are a logical formula for string operations.With some specific characters defined in advance, and combinations of these specific characters,Form a "rule string", this "rule string" is used to express a kind of filtering logic for strings.

As an advanced programming language,swift can be said to have absorbed the advantages of many other advanced languages,But one thing is slightly disappointing,It is that swift has not supported regular expressions at the language level so far.

Usefulness of regular expressions:

Determine whether a given string conforms to a certain rule (specially used to manipulate strings)

- telephone number,E-mail,url ...

-Can directly Baidu written by others

-Others really wrote it,And testedWe can use directly

-To write a regular judgment without loopholes,Requires a lot of testing,Usually the end result is very responsible

Filter the filter string,Web Crawler

Replacement text,QQ chat, mixed graphics

Grammatical rules

Use process

Create rules

Create regular expression objects

3.Start matching

Code example

private func check (str:string) {
 //Always use try statements with regular expressions
 do {
  //-1, create rules
  let pattern="[1-9] [0-9] {4,14}"
  //-2. Create regular expression object
  let regex=try nsregularexpression (pattern:pattern, options:nsregularexpressionoptions.caseinsensitive)
  //-3, start matching
  let res=regex.matchesinstring (str, options:nsmatchingoptions (rawvalue:0), range:nsmakerange (0, str.characters.count))
  //output result
  for checkingres in res {
   print ((str as nsstring) .substringwithrange (checkingres.range))
  }
 }
 catch {
  print (error)
 }
}

Several other common methods

//match all the qualified strings in the string, Returns an array of matching nstextcheckingresult
      public func matchesinstring (string:string, options:nsmatchingoptions, range:nsrange)->[nstextcheckingresult]
      //match strings according to rules, Returns the number of matches
      public func numberofmatchesinstring (string:string, options:nsmatchingoptions, range:nsrange)->int
      //match strings according to rules, Returns the nstextcheckingresult of the first matched string
      public func firstmatchinstring (string:string, options:nsmatchingoptions, range:nsrange)->nstextcheckingresult?
      //match strings according to rules, Returns the range of the first matched string
      public func rangeoffirstmatchinstring (string:string, options:nsmatchingoptions, range:nsrange)->nsrange

Use subclasses to match dates, addresses, and urls

See the official website documentation explanation,It can be known that this nsdatadetector is mainly used to match dates, addresses, and urls. Specify the type to match when used

public class nsdatadetector:nsregularexpression {
 //all instance variables are private
 /* nsdatadetector is a specialized subclass of nsregularexpression. instead of finding matches to regular expression patterns, it matches items identified by data detectors, such as dates, addresses, and urls. the checkingtypes argument should contain one or more of the types nstextcheckingtypedate, nstextcheckingtypeaddress , nstextcheckingtypelink, nstextcheckingtypephonenumber, and nstextcheckingtypetransitinformation. the nstextcheckingresult instances returned will be of the appropriate types from that list.
 * /
 public init (types checkingtypes:nstextcheckingtypes) throws
 public var checkingtypes:nstextcheckingtypes {get}
}
//this is the type selection
 public static var date:nstextcheckingtype {get} //date/time detection
 public static var address:nstextcheckingtype {get} //address detection
 public static var link:nstextcheckingtype {get} //link detection

nsdatadetector get url example

/**
Match urls in a string
-parameter str:the string to match
* /
private func geturl (str:string) {
 //create a regular expression object
 do {
  let datadetector=try nsdatadetector (types:nstextcheckingtypes (nstextcheckingtype.link.rawvalue))
  //matches a string,Return result set
  let res=datadetector.matchesinstring (str, options:nsmatchingoptions (rawvalue:0), range:nsmakerange (0, str.characters.count))
  //get the result
  for checkingres in res {
   print ((str as nsstring) .substringwithrange (checkingres.range))
  }
 }
 catch {
  print (error)
 }
}

". *?" can meet some basic matching requirements

If i want to match multiple rules at the same time, you can use "|"

Replace text in a string with an expression

/**
Show emoticons in characters
-parameter str:match string
* /
private func getemoji (str:string) {
 let strm=nsmutableattributedstring (string:str)
 do {
  let pattern="\\ [. *?\\]"
  let regex=try nsregularexpression (pattern:pattern, options:nsregularexpressionoptions.caseinsensitive)
  let res=regex.matchesinstring (str, options:nsmatchingoptions (rawvalue:0), range:nsmakerange (0, str.characters.count))
  var count=res.count
  //Reverse the text expression
  while count>0 {
   let checkingres=res [-count]
   let tempstr=(str as nsstring) .substringwithrange (checkingres.range)
   //convert string to expression
   if let emoticon=emoticonpackage.emoticonwithstr (tempstr) {
    print (emoticon.chs)
    let attrstr=emoticontextattachment.imagetext (emoticon, font:18)
    strm.replacecharactersinrange (checkingres.range, withattributedstring:attrstr)
   }
  }
  print (strm)
  //replace string,Display to label
  emoticonlabel.attributedtext=strm
 }
 catch {
  print (error)
 }
}

textkit highlight URL

Three main classes are used

nstextstorage

nslayoutmanager

nstextcontainer

Custom uilabel for URL highlighting

1.Define the attributes to be used

/*
 As long as the content in textstorage changes, You can tell layoutmanager to re-layout
 layoutmanager re-layout needs to know where to draw, So the layoutmanager will draw the area drawn by the textcontainer
 * /
 //Standards are used to store content
 //layoutmanager in textstorage
 private lazy var textstorage=nstextstorage ()
 //dedicated to managing layout
 //textmantainer in layoutmanager
 private lazy var layoutmanager=nslayoutmanager ()
 //specifically used to specify the area to draw
 private lazy var textcontainer=nstextcontainer ()
 override init (frame:cgrect) {
   super.init (frame:frame)
   setupsystem ()
 }
 required init?(coder adecoder:nscoder) {
   super.init (coder:adecoder)
   setupsystem ()
 }
 private func setupsystem ()
 {
   //1.Add layoutmanager to textstorage
   textstorage.addlayoutmanager (layoutmanager)
   //2.Add textcontainer to layoutmanager
   layoutmanager.addtextcontainer (textcontainer)
 }
 override func layoutsubviews () {
   super.layoutsubviews ()
  //3.specified area
   textcontainer.size=bounds.size
 }

2.Override the text attribute of the label

override var text:string?
  {
  didset {
 //1. Modify the content stored by textstorage
 textstorage.setattributedstring (nsattributedstring (string:text!))
 //2.Set the textstorage property
 textstorage.addattribute (nsfontattributename, value:uifont.systemfontofsize (20), range:nsmakerange (0, text! .characters.count))
 //3.Process the url
 self.urlregex ()
 //2.Notify layoutmanager to re-layout
 setneedsdisplay ()
  }
}

Matching strings

func urlregex ()
 {
  //1. create a regular expression object
  do {
   let datadetector=try nsdatadetector (types:nstextcheckingtypes (nstextcheckingtype.link.rawvalue))
   let res=datadetector.matchesinstring (textstorage.string, options:nsmatchingoptions (rawvalue:0), range:nsmakerange (0, textstorage.string.characters.count))
   //4 take out the result
   for checkingres in res
   {
    let str=(textstorage.string as nsstring) .substringwithrange (checkingres.range)
    let tempstr=nsmutableattributedstring (string:str)
//tempstr.addattribute (nsforegroundcolorattributename, value:uicolor.redcolor (), range:nsmakerange (0, str.characters.count))
    tempstr.addattributes ([nsfontattributename:uifont.systemfontofsize (20), nsforegroundcolorattributename:uicolor.redcolor ()], range:nsmakerange (0, str.characters.count))
    textstorage.replacecharactersinrange (checkingres.range, withattributedstring:tempstr)
   }
  } catch
  {
   print (error)
  }
 }

4.Redraw text

//If it is uilabel calling the setneedsdisplay method, the system will trigger drawtextinrect
override func drawtextinrect (rect:cgrect) {
 //redraw
 //glyph:understood as a small uiview
 /*
 First parameter:specify the range to draw
 Second parameter:specify where to start drawing
 * /
 layoutmanager.drawglyphsforglyphrange (nsmakerange (0, text! .characters.count), atpoint:cgpointzero)
}

Get click on url in label

If i want to get the click of the url, you must get the range of the click

override func touchesbegan (touches:set<uitouch> ;, withevent event:uievent?) {
 //1.Get the location where the finger clicked
 let touch=(touches as nsset) .anyobject ()!
 let point=touch.locationinview (touch.view)
 print (point)
 //2.Get the url area
 //Note:there is no way to set the range of uitextrange directly
 let range=nsmakerange (10, 20)
 //As long as selectedrange is set, then it is equivalent to setting selectedtextrange
 selectedrange=range
 //Given the specified range, return the rect of the string corresponding to range
 //The reason for returning the array is because the text may wrap
 let array=selectionrectsforrange (selectedtextrange!)
 for selectionrect in array {
   if cgrectcontainspoint (selectionrect.rect, point) {
    print ("URL clicked")
   }
 }
}

The above is the summary of regular expressions in swift that we introduce to you.Hope you like it.

  • Previous How to configure multiple domain names under WampServer
  • Next Java implementation of socket client connection server