Regular expressions in Swift#5
Regular expressions in Swift#5mephistophele-s wants to merge 1 commit intoHowProgrammingWorks:masterfrom mephistophele-s:master
Conversation
Gagnant
left a comment
There was a problem hiding this comment.
- Please check your Match sample.
[0-9]will match only single digits, maybe it should be[0-9]+to match numbers. - Check you Split sample. If original string is
Th//is-is-st, splitter is-, stop is//. The string will be splitted in [th, is, is, st] which is wrong.
| let testString = "one 1 two 2 three 3" | ||
|
|
||
| let pattern = "[0-9]" // Matching numbers | ||
| let nsString = testString as NSString // Cating to NSString to use special methods |
There was a problem hiding this comment.
I supposed "Cating" should be "Casting". And maybe not "special" but "specific".
| var replaceRegExp: NSRegularExpression? | ||
|
|
||
| do { | ||
| replaceRegExp = try NSRegularExpression(pattern: "World", options: .allowCommentsAndWhitespace) |
There was a problem hiding this comment.
If you are not stopping an execution on NSRegularExpression initialization failure, you may replace replaceRegExp declaration with: let replaceRegExp = try? NSRegularExpression(pattern: "World", options: .allowCommentsAndWhitespace).
|
@anastasiaSTR, check this implementation. Feel free to ask me some questions. extension String {
private var range: NSRange {
return NSMakeRange(0, self.utf16.count)
}
private var stringBegin: NSRange {
return NSMakeRange(0, 0)
}
private var stringEnd: NSRange {
return NSMakeRange(utf16.count, 0)
}
public func components(separatedBy regex: NSRegularExpression) -> [String] {
let matchedRanges = regex.matches(in: self, range: self.range).map {
return $0.range
}
return zip(matchedRanges + [stringEnd], [stringBegin] + matchedRanges).flatMap { next, current -> String? in
let start = String.UTF16Index(current.location + current.length)
let end = String.UTF16Index(next.location)
return String(utf16[start ..< end])
}.flatMap {
$0.isEmpty ? nil : $0
}
}
}You may use it in following manner. let targetString = "This-is-string-to-split-by-sp//ecial-character"
if let regex = try? NSRegularExpression(pattern: "-") {
print(targetString.components(separatedBy: regex))
} |
|
|
||
| // Trying to initialize regex | ||
| do { | ||
| let regex = try NSRegularExpression(pattern: pattern, options: []) |
There was a problem hiding this comment.
I propose you to omit options parameter because it has default value []
| // Trying to initialize regex | ||
| do { | ||
| let regex = try NSRegularExpression(pattern: pattern, options: []) | ||
| let results = regex.matches(in: testString, options: [], range: NSMakeRange(0, testString.characters.count)) // Matches |
There was a problem hiding this comment.
You must use testString.utf16.count here. Because NSRegularExpression works with NSString, which are utf16 encoded.
No description provided.