shadowfacts.net/site/posts/2019-01-02-reincarnation.md

44 lines
1.4 KiB
Markdown
Raw Normal View History

2019-01-04 18:14:53 +00:00
```
metadata.title = "Reincarnation"
metadata.category = "meta"
metadata.date = "2019-01-02 23:02:42 -0400"
```
Welcome, to ***Reincarnation***.
<!-- excerpt-end -->
`// TODO: write the actual blog post`
```swift
import Foundation
public struct CharacterCounter {
static let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
static let mention = try! NSRegularExpression(pattern: "(@[a-z0-9_]+)(?:@[a-z0-9\\-\\.]+[a-z0-9]+)?", options: .caseInsensitive)
public static func count(text: String) -> Int {
let mentionsRemoved = removeMentions(in: text)
var count = mentionsRemoved.count
for match in linkDetector.matches(in: mentionsRemoved, options: [], range: NSRange(location: 0, length: mentionsRemoved.utf16.count)) {
count -= match.range.length
count += 23 // Mastodon link length
}
return count
}
private static func removeMentions(in text: String) -> String {
var mut = text
for match in mention.matches(in: mut, options: [], range: NSRange(location: 0, length: mut.utf16.count)).reversed() {
let replacement = mut[Range(match.range(at: 1), in: mut)!]
mut.replaceSubrange(Range(match.range, in: mut)!, with: replacement)
}
return mut
}
}
```
<figure>
<img src="https://github.com/shadowfacts.png" alt="Test" />
<figcaption>Example photo</figcaption>
</figure>