Skip to content

Instantly share code, notes, and snippets.

@mironal
Created April 15, 2024 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mironal/e90f705b5795ce1d62a52bd938a01413 to your computer and use it in GitHub Desktop.
Save mironal/e90f705b5795ce1d62a52bd938a01413 to your computer and use it in GitHub Desktop.
Count the number of characters typed in the Mastodon post screen.
import Foundation
import RegexBuilder
private let urlRegex = Regex {
Capture(.url(scheme: .required))
}
private let mentionRegex = Regex {
Capture {
ChoiceOf {
#/^/#
One(.word.inverted)
}
}
"@"
Capture {
Regex {
Capture {
OneOrMore {
CharacterClass(
.anyOf("_"),
"a" ... "z",
"0" ... "9"
)
}
}
"@"
OneOrMore {
CharacterClass(
.anyOf(".-"),
"a" ... "z",
"0" ... "9"
)
}
OneOrMore {
CharacterClass(
"a" ... "z",
"0" ... "9"
)
}
}
}
}
.ignoresCase()
func count(
status: String,
spoilerText: String?,
charactersReservedPerURL: Int
) -> Int {
let urlFilling = "".padding(toLength: charactersReservedPerURL, withPad: "_", startingAt: 0)
let replaced = status.replacing(urlRegex, with: urlFilling)
.replacing(mentionRegex) { match in
"\(match.output.1)@\(match.output.3)"
}
return replaced.count + (spoilerText?.count ?? 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment