Swift uses Nsdatadetector to extract all links in the string (URL validation)

Source: Internet
Author: User
Tags regular expression uikit


Nsdatadetector is a subclass of the nsregularexpression (regular expression in cocoa) that you can think of as a regular expression match and an incredibly complex expression that can be made from natural language (although perhaps more complex) To extract the information you want.



First,nsdatadetector Introduction




Nsdatadetector is a subclass that inherits from Nsregularexpression. You need to specify the type of information you want to match (date, address, URL, etc.), and you don't have to write complex expressions yourself.




Nsdatadetector Data Detector to detect if it is a link




Nsdatadetector *detector = [nsdatadetector datadetectorwithtypes:nstextcheckingtypelink error:&error];//Create detectors, Detection type is linke (can be changed to detect other)



Nsarray *matches = [Detector matchesinstring:textstring options:0 range:nsmakerange (0, TextString.length)];//detection string



For (Nstextcheckingresult *match in matches) {



if ([match resulttype] = = Nstextcheckingtypelink) {



Nsrange Matchrange = [Match range];



Do something



}



}



Using nsregularexpression because you need to write regular expressions, slightly trouble. We also have a simpler solution for finding data: Nsdatadetector.



The output results are:



Match: <nslinkcheckingresult:0x7510b00>{9, 14}{http://www.isaced.com}
Match: <nsphonenumbercheckingresult:0x8517140>{30, 14}{(023) 52261439}
You can see the nstextcheckingresult as the result output in the block,



Note: When initializing a nsdatadetector, it is OK to specify only the type you want, since adding one extra item will cost more memory.




Second, extract all the URL links in the string



Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let str = "Welcome to visit http://www.111cn.net,https://111cn.net\n and ftp://111cn.net"
Print (Test string: \n\ (str) \ n)

Print ("Matching to:")
Let URLs = Geturls (str)
For URL in URLs {
Print (URL)
}
}

/**
Matches all URLs in a string
*/
Private func Geturls (str:string)-> [String] {
var urls = [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))
Remove results
For Checkingres in res {
Urls.append ((str as nsstring). Substringwithrange (Checkingres.range))
}
}
catch {
Print (Error)
}
return URLs
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}


3, verify that the string is not a valid URL link



Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let str1 = "Welcome to visit Http://www.111cn.net"
Print (STR1)
Print (Verifyurl (STR1))

Let str2 = "Http://www.111cn.net"
Print (STR2)
Print (Verifyurl (STR2))
}

/**
Verify URL format is correct
*/
Private func Verifyurl (str:string)-> Bool {
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))
Judgment result (exact match)
if Res.count = = 1 && res[0].range.location = 0
&& Res[0].range.length = = Str.characters.count {
return True
}
}
catch {
Print (Error)
}
return False
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}


Note: A simpler way to verify URL links
We can also use the Canopenurl () method provided by the system to detect the validity of a link, such as the above example can be changed to the following way:



Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let str1 = "Welcome to visit Http://www.111cn.net"
Print (STR1)
Print (Verifyurl (STR1))

Let str2 = "Http://www.111cn.net"
Print (STR2)
Print (Verifyurl (STR2))
}

/**
Verify URL format is correct
*/
Private func Verifyurl (str:string)-> Bool {
Create a Nsurl instance
If let URL = Nsurl (string:str) {
Detects if the application can open this Nsurl instance
Return Uiapplication.sharedapplication (). Canopenurl (URL)
}
return False
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}


Look at the next NSTextCheckingResult.h file, which can find some of the system for you to set the matching type:


typedef ns_options (uint64_t, Nstextcheckingtype) {//a single type
nstextcheckingtypeorthography = 1ULL << 0,//language identification
nstextcheckingtypespelling = 1ULL << 1,//spell checking
Nstextcheckingtypegrammar = 1ULL << 2,//grammar checking
Nstextcheckingtypedate = 1ULL << 3,//Date/time detection
nstextcheckingtypeaddress = 1ULL << 4,//Address detection
Nstextcheckingtypelink = 1ULL << 5,//link detection
Nstextcheckingtypequote = 1ULL << 6,//Smart Quotes
Nstextcheckingtypedash = 1ULL << 7,//Smart dashes
Nstextcheckingtypereplacement = 1ULL << 8,//fixed replacements, such as copyright symbol for (c)
Nstextcheckingtypecorrection = 1ULL << 9,//AutoCorrection
Nstextcheckingtyperegularexpression ns_enum_available (10_7, 4_0) = 1ULL <<,//Regular expression, MATC Hes
Nstextcheckingtypephonenumber ns_enum_available (10_7, 4_0) = 1ULL << One,//Phone number detection
Nstextcheckingtypetransitinformation ns_enum_available (10_7, 4_0) = 1ULL <<//transit (e.g. flight) I NFO detection
};


Of course, this is only a part of the interception, concrete can point Datadetectorwithtypes method into the NSTextCheckingResult.h file to view.



Nstextcheckingtypedate Date
Duration
TimeZone
Nstextcheckingtypeaddress addresscomponents
Nstextcheckingnamekey
Nstextcheckingjobtitlekey
Nstextcheckingorganizationkey
Nstextcheckingstreetkey
Nstextcheckingcitykey
Nstextcheckingstatekey
Nstextcheckingzipkey
Nstextcheckingcountrykey
Nstextcheckingphonekey
Nstextcheckingtypelink URL
Nstextcheckingtypephonenumber PhoneNumber
Nstextcheckingtypetransitinformation components*
Nstextcheckingairlinekey
Nstextcheckingflightkey



If you want to simply use Nsdatadetector in Uilabel


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.