Summary of regular expressions in Swift _ regular expressions

Source: Internet
Author: User

As an advanced programming language, Swift can say that it absorbs the virtues of many other advanced languages, but one thing is somewhat disappointing, that Swift has so far not supported regular expressions at the linguistic level.

The usefulness of regular expressions:

Determines whether a given string conforms to a rule (specifically for manipulating strings)

-Phone number, e-mail, URL ...

-Can directly Baidu other people to write good regular

-someone else really wrote it and tested it, we can use it directly.

-There is a lot of testing to be written without a bug, usually the end result is very responsible

Filter filter string, web crawler

Replace text, QQ chat, graphic mixed row

Grammar rules

Use process

1. Create rules
2. Creating Regular Expression objects
3. Start the match

code example

Private func Check (str:string) {
 //Use regular expressions Be sure to add a try statement do
 {
  //-1, create a rule 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 { C11/>print ((str as nsstring). Substringwithrange (Checkingres.range))
  }
 catch {
  print (Error)
 }
}

Several other common methods

 Matches all rule-compliant strings in a string, returning the Nstextcheckingresult array that is matched to the public
      func matchesinstring (string:string, Options: Nsmatchingoptions, Range:nsrange)-> [Nstextcheckingresult]      
      //matches the string according to the rule, returns the number of matches to public
      func Numberofmatchesinstring (string:string, Options:nsmatchingoptions, Range:nsrange)-> Int
      
      //to match strings according to the rules, Returns the Nstextcheckingresult public func firstmatchinstring of the first matching string
      (string:string, Options:nsmatchingoptions, Range:nsrange)-> Nstextcheckingresult?
      
      Matches the string according to the rule, returns the range of the first matching string public
      func rangeoffirstmatchinstring (string:string, Options:nsmatchingoptions, Range:nsrange)-> Nsrange

Use subclasses to match dates, addresses, and URLs

Reader Network document Interpretation, you can know that this nsdatadetector is mainly used to match the date, address, and URL. 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, a Ddresses, and URLs. The Checkingtypes argument should contain one or more of the types Nstextcheckingtypedate, nstextcheckingtypeaddress, Nste Xtcheckingtypelink, Nstextcheckingtypephonenumber, and Nstextcheckingtypetransitinformation.
 The Nstextcheckingresult instances returned is the appropriate types from this list.
*/Public init (types checkingtypes:nstextcheckingtypes) throws public var checkingtypes:nstextcheckingtypes {get}} This is type selection public static var date:nstextcheckingtype {get}//Date/time detection public static VAR Address:nstextch Eckingtype {Get}//Address detection public static var link:nstextcheckingtype {get}//Link detection 

Nsdatadetector Get URL Sample

 /**
matching URLs in a string

-parameter str: string to match/
private func getUrl (str:string) {
 //Create a regular expression object
 Do {let
  datadetector = Try Nsdatadetector (types:nstextcheckingtypes (NSTextCheckingType.Link.rawValue))
  // Match string, return result set let
  res = datadetector.matchesinstring (str, options:nsmatchingoptions (rawvalue:0), Range: Nsmakerange (0, Str.characters.count))
  //Fetch result for
  Checkingres in res {
   print (str as nsstring). Substringwithrange (Checkingres.range))
  }
 catch {
  print (Error)
}}

". *?" can meet some basic matching requirements

If you want to match more than one rule at a time, you can connect multiple rules by "|"

Replace text in a string with an expression

/** display character expression-parameter str: matching 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-pull 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)//replacement string, showing to label emoticonlabel.attributedtext = STRM} catch 
{Print (Error)}} 

Textkit to URL highlighting

Mainly used in three classes

Nstextstorage
Nslayoutmanager
Nstextcontainer

Custom Uilabel to implement URL highlighting

1, define the attributes to be used

 /*
 as long as the content in the Textstorage changes, you can notify the LayoutManager to rearrange
 layoutmanager layout needs to know where to draw, So LayoutManager will be textcontainer the area of the plot *//
 to be used for storing content/
 /textstorage in LayoutManager
 private lazy var textstorage = nstextstorage ()
 //dedicated to managing layouts
 //LayoutManager TextContainer
 Private Lazy var LayoutManager = Nslayoutmanager ()
 //dedicated to the area of the specified 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. Specify area
   textcontainer.size = Bounds.size
 }

2, rewrite the label's Text property

Override Var text:string?
  {
  didset{
 //1. Modify the contents of the Textstorage store
 textstorage.setattributedstring (nsattributedstring (string:text!))
 2. Set textstorage properties
 textstorage.addattribute (Nsfontattributename, value:UIFont.systemFontOfSize, Range: Nsmakerange (0, text!. Characters.count)
 //3. Process URL
 self. Urlregex ()
 //2. Notify LayoutManager re-layout
 setneedsdisplay ()
  }
}

3, matching string

 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 out result for checkingres in res {let str = (textstorage.string as Nsst Ring). Substringwithrange (checkingres.range) Let TempStr = nsmutableattributedstring (STRING:STR)//TempStr.addAttrib
    Ute (Nsforegroundcolorattributename, Value:UIColor.redColor (), Range:nsmakerange (0, Str.characters.count)) Tempstr.addattributes ([NSFontAttributeName:UIFont.systemFontOfSize), Nsforegroundcolorattributename: Uicolor.redcolor ()], Range:nsmakerange (0, Str.characters.count)) Textstorage.replacecharactersinrange ( Checkingres.range, Withattributedstring:tempstr)}}catch {print (Error)}} 

4, redrawing the text

 If the Uilabel calls the Setneedsdisplay method, the system will promote Drawtextinrect
override func Drawtextinrect (rect:cgrect) {
 //
 Redraw Glyph: Understood as a small uiview/
 *
 First parameter: Specifies the range to draw the
 second parameter: Specifies where to start drawing/
 Layoutmanager.drawglyphsforglyphrange (Nsmakerange (0, text!). Characters.count), Atpoint:cgpointzero)
}

Gets the click of the URL in the label

If you want to get a click of the URL, you must get the range of clicks

 Override Func Touchesbegan (touches:set<uitouch>, withevent event:uievent?) {
 //1, get the position of the finger click let touch
 = (touches as Nsset). Anyobject ()!
 Let point = Touch.locationinview (Touch.view)
 print (point)
 //2, Get URL area
 //NOTE: There is no way to directly set the scope of Uitextrange
 Let range = Nsmakerange
 //As long as the selectedrange is set, it is equivalent to setting the Selectedtextrange
 Selectedrange = Range /////////
 rect the
 array is returned because the text may be wrapped let
 array = Selectionrectsforrange, given the specified range ( selectedtextrange!)
 For Selectionrect in array {
   if Cgrectcontainspoint (Selectionrect.rect, point) {
    print ("Clicked URL")
   }
 }
}

The above content is small make up with you introduce Swift's regular expression summary, hope everybody likes.

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.