mirror of
https://github.com/DiscordSRV/Ascension.git
synced 2024-10-31 08:32:18 +01:00
Ignore markdown characters inside links
This commit is contained in:
parent
7ec2fe877c
commit
b17e912597
@ -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, '*', '_', '|', '`', '~', ':', '[');
|
||||
}
|
||||
|
||||
private static String escapeChars(String input, char... characters) {
|
||||
for (char character : characters) {
|
||||
input = input.replace(
|
||||
String.valueOf(character),
|
||||
"\\" + character);
|
||||
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();
|
||||
}
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user