using System.Text.RegularExpressions;
namespace MeloongCore;
public static class EscapeUtils {
///
/// XML 转义。
///
public static string? XmlEscape(string? str) {
if (str is null) return null;
if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str
.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("'", "'")
.Replace("\"", """).ReplaceLineEndings("
");
}
///
/// VB.NET 的 Like 关键字转义。
///
public static string LikePatternEscape(string input) {
var builder = new StringBuilder();
foreach (char c in input) {
if (c is '[' or ']' or '*' or '?' or '#') {
builder.Append('[').Append(c).Append(']');
} else {
builder.Append(c);
}
}
return builder.ToString();
}
///
/// 正则表达式转义。等同于 Regex.Escape。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexEscape(string? value) => Regex.Escape(value);
///
/// 正则表达式去转义。等同于 Regex.Unescape。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexUnescape(string? value) => Regex.Unescape(value);
///
/// URL 转义。等同于 Uri.EscapeDataString。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlEscape(string? value) => Uri.EscapeDataString(value);
///
/// URL 去转义。等同于 Uri.UnescapeDataString。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlUnescape(string? value) => Uri.UnescapeDataString(value);
///
/// 表单转义。等同于 WebUtility.UrlEncode。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlEscape(string? value) => WebUtility.UrlEncode(value);
///
/// 表单去转义。等同于 WebUtility.UrlDecode。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlUnescape(string? value) => WebUtility.UrlDecode(value);
///
/// HTML 转义。等同于 WebUtility.HtmlEncode。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlEscape(string? value) => WebUtility.HtmlEncode(value);
///
/// HTML 去转义。等同于 WebUtility.HtmlDecode。
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlUnescape(string? value) => WebUtility.HtmlDecode(value);
}