DocSpace-buildtools/web/ASC.Web.Core/Extensions/StringExtension.cs

108 lines
3.5 KiB
C#
Raw Normal View History

2019-06-07 08:59:07 +00:00
namespace System
{
public static class StringExtension
{
private static readonly Regex reStrict = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+"
+ @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
+ @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$");
public static string HtmlEncode(this string str)
{
return !string.IsNullOrEmpty(str) ? HttpUtility.HtmlEncode(str) : str;
}
/// <summary>
/// Replace ' on
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReplaceSingleQuote(this string str)
{
2022-01-13 12:53:57 +00:00
return str?.Replace('\'', '');
2019-06-07 08:59:07 +00:00
}
public static bool TestEmailRegex(this string emailAddress)
{
emailAddress = (emailAddress ?? "").Trim();
return !string.IsNullOrEmpty(emailAddress) && reStrict.IsMatch(emailAddress);
}
public static string GetMD5Hash(this string str)
{
var bytes = Encoding.Unicode.GetBytes(str);
2021-10-01 10:28:15 +00:00
using var CSP = MD5.Create();
2019-06-07 08:59:07 +00:00
var byteHash = CSP.ComputeHash(bytes);
2019-08-15 13:16:39 +00:00
return byteHash.Aggregate(string.Empty, (current, b) => current + string.Format("{0:x2}", b));
2019-06-07 08:59:07 +00:00
}
public static int EnumerableComparer(this string x, string y)
{
var xIndex = 0;
var yIndex = 0;
while (xIndex < x.Length)
{
if (yIndex >= y.Length)
return 1;
if (char.IsDigit(x[xIndex]) && char.IsDigit(y[yIndex]))
{
var xBuilder = new StringBuilder();
while (xIndex < x.Length && char.IsDigit(x[xIndex]))
{
xBuilder.Append(x[xIndex++]);
}
var yBuilder = new StringBuilder();
while (yIndex < y.Length && char.IsDigit(y[yIndex]))
{
yBuilder.Append(y[yIndex++]);
}
long xValue;
try
{
xValue = Convert.ToInt64(xBuilder.ToString());
}
catch (OverflowException)
{
2019-08-15 13:16:39 +00:00
xValue = long.MaxValue;
2019-06-07 08:59:07 +00:00
}
long yValue;
try
{
yValue = Convert.ToInt64(yBuilder.ToString());
}
catch (OverflowException)
{
2019-08-15 13:16:39 +00:00
yValue = long.MaxValue;
2019-06-07 08:59:07 +00:00
}
int difference;
if ((difference = xValue.CompareTo(yValue)) != 0)
return difference;
}
else
{
int difference;
if ((difference = string.Compare(x[xIndex].ToString(CultureInfo.InvariantCulture), y[yIndex].ToString(CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase)) != 0)
return difference;
xIndex++;
yIndex++;
}
}
if (yIndex < y.Length)
return -1;
return 0;
}
}
}