Ignore markdown characters inside links

This commit is contained in:
Vankka 2024-06-22 12:07:59 +03:00
parent 7ec2fe877c
commit b17e912597
No known key found for this signature in database
GPG Key ID: 62E48025ED4E7EBB

View File

@ -23,10 +23,27 @@
package com.discordsrv.api.discord.util;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class DiscordFormattingUtil {
// If first group is present the match will be ignored
private static final List<Character> FORMATTING_CHARACTERS = Arrays.asList('*', '_', '|', '`', '~', ':', '[');
private static final Pattern FORMATTING_PATTERN = Pattern.compile(
"(https?://.*\\.[^ ]*)?"
+ "(["
+ FORMATTING_CHARACTERS.stream()
.map(character -> Pattern.quote(String.valueOf(character)))
.collect(Collectors.joining())
+ "])"
);
private static final Pattern QUOTE_PATTERN = Pattern.compile("(^|\n)>");
private static final Pattern MENTION_PATTERN = Pattern.compile("(<[@#][0-9]{16,20}>)");
private DiscordFormattingUtil() {}
public static String escapeContent(String content) {
@ -37,23 +54,24 @@ public final class DiscordFormattingUtil {
}
public static String escapeFormatting(String content) {
return escapeChars(content, '*', '_', '|', '`', '~', ':', '[');
Matcher matcher = FORMATTING_PATTERN.matcher(content);
StringBuffer output = new StringBuffer();
int lastEnd = 0;
while (matcher.find()) {
if (matcher.group(1) == null) {
matcher.appendReplacement(output, Matcher.quoteReplacement("\\" + matcher.group(2)));
lastEnd = matcher.end();
}
private static String escapeChars(String input, char... characters) {
for (char character : characters) {
input = input.replace(
String.valueOf(character),
"\\" + character);
}
return input;
output.append(content.substring(lastEnd));
return output.toString();
}
public static String escapeQuotes(String input) {
return input.replaceAll("^>", Matcher.quoteReplacement("\\>"));
return QUOTE_PATTERN.matcher(input).replaceAll("$1" + Matcher.quoteReplacement("\\>"));
}
public static String escapeMentions(String input) {
return input.replaceAll("<([@#])", Matcher.quoteReplacement("\\<") + "$1");
return MENTION_PATTERN.matcher(input).replaceAll(Matcher.quoteReplacement("\\") + "$1");
}
}