In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to correctly use regular expressions in swift. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
The use of regular expressions:
Determine whether a given string conforms to a certain rule (specifically for manipulating strings)
-phone number, email address, URL...
-you can directly write the rules written by Baidu.
-someone else has really written it and tested it, so we can use it directly.
-to write a bug-free regular judgment requires a lot of testing, and the end result is usually very responsible
Filter filter string, web crawler
Replace text, QQ chat, mixed picture and text
rule of grammar
Use process
1. Create a rule
2. Create a regular expression object
3. Start to match
Code example
Private func check (str: String) {/ / when using regular expressions, be sure to add the try statement do {/ /-1, create the rule let pattern = "[1-9] [0-9] {4let res 14}" / /-2, create the regular expression object let regex = try NSRegular_Expression (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 matching strings in the string, return the matched NSTextCheckingResult array public func matchesInString (string: String, options: NSMatchingOptions, range: NSRange)-> [NSTextCheckingResult] / / match the string according to the rule, and return the number of matched public func numberOfMatchesInString (string: String, options: NSMatchingOptions, range: NSRange)-> Int / / match the string according to the rule. Returns the NSTextCheckingResult public func firstMatchInString of the first matched string (string: String, options: NSMatchingOptions, range: NSRange)-> NSTextCheckingResult? / / matches the string according to the rules, and 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 URL
Looking at the documentation on the official website, you can see that this NSDataDetector is mainly used to match dates, addresses, and URL. Specify the type to match when using
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- parameter str in string: 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 the result for checkingRes in res {print ((str as NSString) .substringWithRange (checkingRes.range))}} catch {print (error)}}
". *?" It can meet some basic matching requirements.
If you want to match multiple rules at the same time, you can connect multiple rules with "|"
Replace Chinese characters in a string with facial expressions
/ * * the emoji in the display character-parameter str: match string * / private func getEmoji (str:String) {let strM = NSMutableAttributedString (string: str) do {let pattern = "\ [. *?\]" let regex = try NSRegular_Expression (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 take out text emoji while count > 0 {let checkingRes = res [--count] let tempStr = (str as NSString) .substringWithRange (checkingRes.range) / / convert string to emoji 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, displayed to label emoticonLabel.attributedText = strM} catch {print (error)}}
TextKit highlights URL
Three main classes are used.
NSTextStorage
NSLayoutManager
NSTextContainer
Customize UILabel to achieve url highlighting
1. Define the attributes to be used
/ * whenever the content in textStorage changes, you can tell layoutManager to relayout layoutManager and relayout needs to know where to draw. So layoutManager will write that the area drawn by textContainer * / / textStorage that we use to store content has layoutManager private lazy var textStorage = NSTextStorage () / / dedicated to managing layouts / / layoutManager has textContainer private lazy var layoutManager = NSLayoutManager () / / dedicated to specifying the area drawn 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. Override the text attribute of label
Override var text: String? {didSet {/ / 1. Modify the content stored in textStorage textStorage.setAttributedString (NSAttributedString (string: text!)) / / 2. Set the properties of textStorage textStorage.addAttribute (NSFontAttributeName, value: UIFont.systemFontOfSize (20), range: NSMakeRange (0, textroom.accouns.count) / / 3. Deal with URL self.URLRegex () / / 2. Notify layoutManager to relayout setNeedsDisplay ()}}
3. Match 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 fetch 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 the text
/ / if the setNeedsDisplay method is called by UILabel, the system will prompt drawTextInRectoverride func drawTextInRect (rect: CGRect) {/ / redraw / / glyph: understood as a small UIView / * the first parameter: specify the range of drawing; the second parameter: specify where to start drawing * / layoutManager.drawGlyphsForGlyphRange (NSMakeRange (0, textroom.illustrs.count), atPoint: CGPointZero)}
Get the click of URL in label
If you want to get clicks on URL, you must get the range of clicks
Override func touchesBegan (touches: Set, withEvent event: UIEvent?) {/ / 1, get the position of the finger 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 directly set the range of UITextRange let range = NSMakeRange (10,20) / / as long as you set selectedRange, it is equivalent to setting selectedTextRange selectedRange = range / / given the specified range, and returning the rect / / return array of the string corresponding to range because the text may wrap let array = selectionRectsForRange (selectedTextRange!) For selectionRect in array {if CGRectContainsPoint (selectionRect.rect, point) {print ("clicked URL")} after reading the above, do you have any further understanding of how to correctly use regular expressions in swift? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.