Files
SPT-Server-Build/SptCommon/Extensions/StringExtensions.cs
T
2025-02-07 19:36:17 +00:00

48 lines
1.3 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
namespace SptCommon.Extensions;
public static class StringExtensions
{
private static readonly Dictionary<string, Regex> RegexCache = new();
private static readonly object RegexCacheLock = new();
public static string RegexReplace(this string source, [StringSyntax(StringSyntaxAttribute.Regex)] string regexString, string newValue)
{
Regex regex;
lock (RegexCacheLock)
{
if (!RegexCache.TryGetValue(regexString, out regex))
{
regex = new Regex(regexString);
RegexCache[regexString] = regex;
}
}
return regex.Replace(source, newValue);
}
public static bool RegexMatch(this string source, [StringSyntax(StringSyntaxAttribute.Regex)] string regexString, out Match? matchedString)
{
Regex regex;
lock (RegexCacheLock)
{
if (!RegexCache.TryGetValue(regexString, out regex))
{
regex = new Regex(regexString);
RegexCache[regexString] = regex;
}
}
matchedString = null;
if (!regex.IsMatch(source))
{
return false;
}
matchedString = regex.Match(source);
return true;
}
}