BotSharp/src/Infrastructure/BotSharp.Abstraction/Utilities/StringExtensions.cs

66 lines
1.8 KiB
C#
Raw Normal View History

2023-10-26 18:52:44 +00:00
using System.Text.Json;
2023-08-17 04:04:23 +00:00
using System.Text.RegularExpressions;
2023-07-21 15:15:30 +00:00
namespace BotSharp.Abstraction.Utilities;
public static class StringExtensions
{
public static string IfNullOrEmptyAs(this string str, string defaultValue)
=> string.IsNullOrEmpty(str) ? defaultValue : str;
2023-07-28 03:12:12 +00:00
public static string SubstringMax(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str))
return str;
if (str.Length > maxLength)
return str.Substring(0, maxLength);
else
return str;
}
2023-08-17 04:04:23 +00:00
2023-08-28 18:57:51 +00:00
public static string[] SplitByNewLine(this string input)
{
2023-11-14 14:13:54 +00:00
if (input == null)
{
return new string[0];
}
2023-08-28 18:57:51 +00:00
return input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
2023-11-14 14:13:54 +00:00
public static string RemoveNewLine(this string input)
{
if (input == null)
{
return null;
}
return input.Replace("\r", " ").Replace("\n", " ").Trim();
}
public static bool IsEqualTo(this string str1, string str2, StringComparison option = StringComparison.OrdinalIgnoreCase)
{
return str1.Equals(str2, option);
}
2023-10-26 18:52:44 +00:00
public static string JsonContent(this string text)
{
var m = Regex.Match(text, @"\{(?:[^{}]|(?<open>\{)|(?<-open>\}))+(?(open)(?!))\}");
return m.Success ? m.Value : "{}";
}
public static T? JsonContent<T>(this string text)
{
text = JsonContent(text);
2023-11-01 21:30:39 +00:00
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
AllowTrailingCommas = true
};
return JsonSerializer.Deserialize<T>(text, options);
2023-10-26 18:52:44 +00:00
}
2023-07-21 15:15:30 +00:00
}