Created
April 15, 2024 06:35
-
-
Save mironal/e90f705b5795ce1d62a52bd938a01413 to your computer and use it in GitHub Desktop.
Count the number of characters typed in the Mastodon post screen.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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